Image into byte array in java

The following code will demonstrate on how to write an image into a byte array in java or convert Image

File myImageFile = new File("D:/project/SampleDraw/src/sampleImage.gif");
FileInputStream fis = null;
try {
fis = new FileInputStream(myImageFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = new byte[1024];
byte[] tmp = new byte[0];
byte[] myArrayImage = new byte[0];
int len = 0 ;
int total = 0;
try {
while( (len = fis.read(data)) != -1 ) {
total += len;
tmp = myArrayImage;
myArrayImage = new byte[total];
System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
System.arraycopy(data,0,myArrayImage,tmp.length,len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(myArrayImage.length);

for (int i = 0; i < myArrayImage.length; i++) {
System.out.println(myArrayImage[i]);
}

No comments:

Post a Comment