How to convert byte[] to BufferedImage in Java

This article shows how to convert a byte[] to a BufferedImage in Java.


  InputStream is = new ByteArrayInputStream(bytes);
  BufferedImage bi = ImageIO.read(is);

The idea is puts the byte[] into an ByteArrayInputStream object, and we can use ImageIO.read to convert it to a BufferedImage.

1. Convert byte[] to BufferedImage.

The below example shows how to convert BufferedImage to byte[] and vice versa.

ImageUtils.java

package com.mkyong.io.image;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ImageUtils {

    public static void main(String[] args) throws IOException {

        Path source = Paths.get("c:\\test\\mkyong.png");
        Path target = Paths.get("c:\\test\\mkyong-new.png");

        BufferedImage bi = ImageIO.read(source.toFile());

        // convert BufferedImage to byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "png", baos);
        byte[] bytes = baos.toByteArray();

        // convert byte[] back to a BufferedImage
        InputStream is = new ByteArrayInputStream(bytes);
        BufferedImage newBi = ImageIO.read(is);

        // add a text on top on the image, optional, just for fun
        Graphics2D g = newBi.createGraphics();
        g.setFont(new Font("TimesRoman", Font.BOLD, 30));
        g.setColor(Color.BLACK);
        g.drawString("Hello World", 100, 100);

        // save it
        ImageIO.write(newBi, "png", target.toFile());

    }
}

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

26 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sean
12 years ago

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
11 years ago

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

Harshit
7 years ago
Reply to  Krunal Patel

Import the following classes :
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

Then use the following piece of code:
Graphics g;
Supposing you have image’s byte code in
byte[] img;

Now, this will get you the image.
InputStream in = new ByteArrayInputStream(imgData);
BufferedImage bImageFromConvert = ImageIO.read(in);
g = bImageFromConvert.getGraphics();

// optional statements
g.setColor(Color.red); // to set color
g.setFont(g.getFont().deriveFont(100f)); // to set font style
g.drawString(“Hello”, 100, 200); // to draw any string on it
g.dispose();

vijayalangaram
6 years ago

hi i have image that stored in mongodb as byte format looking for separate decoder for that.

File image = new File(“mongodb://localhost:27017//test-db//user”);
Tesseract tessInst = new Tesseract();
tessInst.setDatapath(“C:\\Users\\Administrator\\Desktop\\tessdata”);
try {
String result= tessInst.doOCR(image);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}

}
}

Jemish Khunt
2 years ago

This is not working in my case if you use webp image we get null data BufferedImage newBi

Ali Bahadar
7 years ago

Hi,
Is there any way to convert multipartfile file of type webp rfrmat to png ?

Shriman Nijagun
8 years ago

Do we have any other option otherthan ImageIO.read for converting Bytes to BufferedImage
Because when reading via ImageIO.read,image size is increasing…

moh
8 years ago

thanks it works

Francis
8 years ago

ImageIO.read() is very, VERY slow (even without disk cache) – please offer a better solution. Thanks in advance

Edison Quisiguina
12 years ago

Thanks a Lot 🙂

God bless you (Y)

Guilherme
12 years ago

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

Eddy
12 years ago

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
12 years ago

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

Alexander
12 years ago

Thx a lot!

Subhash
13 years ago

thank you so much

Jacek
13 years ago

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.

nico
13 years ago

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

Deniz
13 years ago

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

junaid
13 years ago

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
14 years ago

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

umer
14 years ago

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

Mikhail
14 years ago

Thank you!

Alexander
15 years ago

Help me a lot, Thank you.

dilla
15 years ago

Great code.. much help.. thx

reza
15 years ago

thanks a lot
it was useful for me.

god bless you

aashish
16 years ago

awesome code, helped me today…
thank you
Aashish Dalmia