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);
compass app flashLight app

3 comments:

  1. It is nice article to improve my knowledge.thank you for sharing useful post
    visit
    web programming tutorial
    welookups

    ReplyDelete
  2. Appreciating the dedication you put into your website and detailed information you present. It's nice to come across a blog every once in a while that isn't the same outdated rehashed information. Great read! I've saved your site and I'm adding your RSS feeds to my Google account.audience

    ReplyDelete
  3. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.

    sme working capital loan

    sme loan singapore

    business loans

    pr application

    bhutan travel

    meditation

    small business loan Singapore

    bitcoin trading

    bitcoin trading

    sme loan singapore

    digital assets

    ReplyDelete