How to convert byte[] to BufferedImage in Java

The conversion from byte[] to BufferedImage is involved the use of InputStream and ImageIO.read as following :


InputStream in = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(in);

The following example will read an image file named “darksouls.jpg“, convert it into byte array, and then reuse the converted byte array, and convert it back to a new BufferedImage, and save it back into a new name “new-darksouls.jpg“.


package com.mkyong.image;

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;

public class ImageTest {

	public static void main(String[] args) {

		try {

			byte[] imageInByte;
			BufferedImage originalImage = ImageIO.read(new File(
					"c:/darksouls.jpg"));

			// convert BufferedImage to byte array
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(originalImage, "jpg", baos);
			baos.flush();
			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:/new-darksouls.jpg"));

		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
32 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
29 Comment authors
Shriman NijagunmohFrancisKrunal PatelSatheeshraj V Recent comment authors
newest oldest most voted
Sean
Guest
Sean

Hi,
this solution is only valid when you read image from a file. But when reading a byte array from a database the following error shows up:

Exception in thread “main” java.lang.IllegalArgumentException: im == null!
at javax.imageio.ImageIO.write(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)

Krunal Patel
Guest
Krunal Patel

I have image in binary format file how to get back image .there is concpt of ImageIO and ByteBuffer .but How i use this

moh
Guest
moh

thanks it works

Satheeshraj V
Guest
Satheeshraj V

Hi,
How to resize the animated gif image. Please help me.

Regards,
Satheesh V

Edison Quisiguina
Guest
Edison Quisiguina

Thanks a Lot :)

God bless you (Y)

Guilherme
Guest
Guilherme

If anybody are getting this:

Exception in thread “main” java.lang.IllegalArgumentException: im == null!

Try this -> http://myjeeva.com/how-to-convert-image-to-string-and-string-to-image-in-java.html

It must help ! xD

trackback
Suggestions to load data faster | BlogoSfera

[…] the code above, is that result I’m getting? And probably one of the solutions could be: http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/ […]

trackback
Suggestions to load data faster | Android Questions

[…] the code above, is that result I’m getting? And probably one of the solutions could be: http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/ […]

Eddy
Guest
Eddy

Hi, I use richfaces treenode because there are some problems on primefaces treenode. I need to load an image inside from a byte array (blob type in my database).

Is it necessary to declare the icon url into iconLeaf param?
I mean, is it necessary to create an image file to get it inside the treenode or can i get a buffered image directly from the bean?
BR.

bamobravo
Guest
bamobravo

i got a null pointer exception.
please what could be wrong?
thanks in advance.

Alexander
Guest
Alexander

Thx a lot!

Subhash
Guest
Subhash

thank you so much

Amir Husain Meysami (???? ???? ?????)
Guest
Amir Husain Meysami (???? ???? ?????)

Thank You Mr.Yong
God Bless u.

Jacek
Guest
Jacek

Hi.
I read form file to byte array. In next step i change image size and write as byte array to screen. It’s work fine.
Thanks for tutorial.

trackback
Struts 2 dynamic image example

[…] Convert image to bytes of array in Java […]

nico
Guest
nico

i need help on showing images from database to my jsp page. I am using Spring+Hibernate Framework. i am getting String when i get the blob from the pojo. can i get image directly from the pojo? thanks

Manuel
Guest
Manuel

Hola Amigos .. aca tengo una duda .. veo la imagen en mi aplicacion y todo bien .. el problema es como hago para guardar la imagen capturda de una webcam .. trate de acer esto . pero solo llege hasta aqui !! …

try{

Image img=null;
FrameGrabbingControl fgc = (FrameGrabbingControl)
player.getControl(“javax.media.control.FrameGrabbingControl”);
Buffer buf = fgc.grabFrame();
// creamos la imagen awt
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);

if (img != null)
{

ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) img, “JPEG”, out);
InputStream in = new ByteArrayInputStream(out.toByteArray());

// ——————————————————————————————————————————-
// AQUI COMO AGO PARA CONVERTIR LA IMAGEN A BYTE :.. PARA GUARDARLO EN BD SQL
// ——————————————————————————————————————————-

}catch(Exception ex){}ç

Deniz
Guest
Deniz

Thanks a lot for this and other nice and handy tutorials.

junaid
Guest
junaid

Hello All,
I want to convert raw file to jpg.
I have file name ss.raw. I want to convert it into ss.jpg. Please help me.
Thanks in Advance.

Shark
Guest
Shark

How to read images from HDFS in map-reduce??

Bhavesh
Guest
Bhavesh

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication3; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; /** * * @author Bhavesh */ public class JavaApplication3 { public static void main(String[] args) { // TODO code application logic here try { InputStream in = new ByteArrayInputStream(hexToBytes("CD302C16E7D853D5A9012AB7AD3C35310EDD55AFAE1618738C938300F43F852608A0600D2D00381C5381CD301D4B8A042814EC50025324380681922279717B9A4A620A36D9A889E6A0A400D3BAD265125ADA")); BufferedImage bImageFromConvert = ImageIO.read(in); ImageIO.write(bImageFromConvert, "jpg", new File("f:/new-darksouls.jpg")); } catch (IOException e) { System.out.println(e.getMessage()); } } public static byte[] hexToBytes(char[] hex) { int length = hex.length / 2; byte[] raw = new byte[length]; for (int i = 0;… Read more »

umer
Guest
umer

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

Jason
Guest
Jason

Hi Mkyong,

 
InputStream in = new ByteArrayInputStream(rsvalue.getBytes(10));
BufferedImage bImageFromConvert = ImageIO.read(in);
	             
ImageIO.write(bImageFromConvert, "jpg", new File("D:\\"+ rsvalue.getString(2) +".jpg")); 

I having this error :

Exception in thread “main” java.lang.IllegalArgumentException: im == null!

Mikhail
Guest
Mikhail

Thank you!

Guillermo
Guest
Guillermo

Excelente ejemplo! Gracias.

Alexander
Guest
Alexander

Help me a lot, Thank you.

dilla
Guest
dilla

Great code.. much help.. thx

reza
Guest
reza

thanks a lot
it was useful for me.

god bless you

binnu
Guest
binnu

Tu java na..mei k aaj ko hu…

aashish
Guest
aashish

awesome code, helped me today…
thank you
Aashish Dalmia