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());
		}
	}
}
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Edison Quisiguina

    Thanks a Lot :)

    God bless you (Y)

  • 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

  • Pingback: Suggestions to load data faster | BlogoSfera()

  • Pingback: Suggestions to load data faster | Android Questions()

  • 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)

  • 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

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

  • Alexander

    Thx a lot!

  • Subhash

    thank you so much

  • http://racleadf.blogfa.com Amir Husain Meysami (???? ???? ?????)

    Thank You Mr.Yong
    God Bless u.

  • http://jacek.podgorz.pl 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.

  • Pingback: Struts 2 dynamic image example()

  • 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

  • http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/ 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

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

  • 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

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

  • 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; i < length; i++) {
          int high = Character.digit(hex[i * 2], 16);
          int low = Character.digit(hex[i * 2 + 1], 16);
          int value = (high << 4) | low;
          if (value > 127)
            value -= 256;
          raw[i] = (byte) value;
        }
        return raw;
      }
     
      public static byte[] hexToBytes(String hex) {
        return hexToBytes(hex.toCharArray());
      }
    }

    i got this error..

    Exception in thread “main” java.lang.IllegalArgumentException: im == null!
    at javax.imageio.ImageIO.write(ImageIO.java:1457)
    at javax.imageio.ImageIO.write(ImageIO.java:1521)
    at javaapplication3.JavaApplication3.main(JavaApplication3.java:48)
    Java Result: 1

    please help me

  • 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

    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

    Thank you!

  • Guillermo

    Excelente ejemplo! Gracias.

  • http://www.har1.com.co Alexander

    Help me a lot, Thank you.

  • dilla

    Great code.. much help.. thx

  • reza

    thanks a lot
    it was useful for me.

    god bless you

  • http://www.desisewada.com binnu

    Tu java na..mei k aaj ko hu…

  • aashish

    awesome code, helped me today…
    thank you
    Aashish Dalmia