How to convert byte[] to BufferedImage in Java
Published: September 29, 2009 , Updated: March 30, 2010 , Author: mkyong
The conversion from byte[] to BufferedImage is involved InputStream and ImageIO.read as follow :
InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in);
Example
This class will read an image file, convert it to byte array , and then convert it back to BufferedImage, finally save it to a new location.
import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; /* * @author mkyong * */ public class ImageTest { public static void main(String [] args){ try{ BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mypic.jpg")); //convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write( originalImage, "jpg", baos ); baos.flush(); byte[] imageInByte = baos.toByteArray(); baos.close(); //convert byte array back to BufferedImage InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in); ImageIO.write(bImageFromConvert, "jpg", new File("c:\\image\\mypic_new.jpg")); }catch(IOException e){ System.out.println(e.getMessage()); } } }
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
hi,
how can i read image in byte array from socket and write a jpeg file, please help me here is my email umer_rock_12[at]hotmail.com
Thanks and Regards
umer
Hi Mkyong,
I having this error :
Exception in thread “main” java.lang.IllegalArgumentException: im == null!
Thank you!
Excelente ejemplo! Gracias.
Help me a lot, Thank you.
Great code.. much help.. thx
thanks a lot
it was useful for me.
god bless you
Tu java na..mei k aaj ko hu…
awesome code, helped me today…
thank you
Aashish Dalmia