Saturday, July 20, 2013

BufferedImage to byte array

Sometimes it is worth to convert from a buffered image object to an array of bytes for later use in your program. You can do this by using the write(BufferedImage bi,String type,OutputStream os) method of the ImageIO class. See the example code below:

public void BufferedImageToByteArray(String filename){
try{

BufferedImage orImage=ImageIO.read(new File(filename));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(orImage, "jpg", baos );
byte[] imageBytes=baos.toByteArray();
//do something with the byte array

}catch(IOException ie){}
}


In the example above, the data of an image is read by using the read method of the ImageIO class. This image data is stored in the orImage, BufferedImage object variable. The ByteArrayOutputStream object is constructed so it is ready to accept the image data. The write method of the ImageIO class is used to write or transfer the data to the ByteArrayOutputStream object. The ByteArrayOutputStream has a method call toByteArray that can return the image data in an array of bytes.

If you would like to convert back from the byte array to an buffered image object, you need to use the ByteArrayIntputStream class to read the byte array in to the ByteArrayIntputStream object. Then use the read(InputStream) method of the ImageIO to return a buffered image object.

ByteArrayInputStream bais=new ByteArrayInputStream(imageBytes);
BufferedImage bi=ImageIO.read(bais);

No comments:

Post a Comment