How to convert a byte[] to a BufferedImage in Java?

Try this:

private BufferedImage createImageFromBytes(byte[] imageData) {
    ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
    try {
        return ImageIO.read(bais);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

I have tried the approaches mentioned here but for some reason neither of them worked. Using ByteArrayInputStream and ImageIO.read(...) returns null, whereas byte[] array = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); returns a copy of the image data, not a direct reference to them (see also here).

However, the following worked for me. Let's suppose that the dimensions and the type of the image data are known. Let also byte[] srcbuf be the buffer of the data to be converted into BufferedImage. Then,

  1. Create a blank image, for example

    img=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    
  2. Convert the data array to Raster and use setData to fill the image, i.e.

    img.setData(Raster.createRaster(img.getSampleModel(), new DataBufferByte(srcbuf, srcbuf.length), new Point() ) );
    

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
byte[] array = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(pixelArray, 0, array, 0, array.length);

This method does tend to get out of sync when you try to use the Graphics object of the resulting image. If you need to draw on top of your image, construct a second image (which can be persistant, i.e. not constructed every time but re-used) and drawImage the first one onto it.


Several people upvoted the comment that the accepted answer is wrong.

If the accepted answer isn't working, it may be because Image.IO doesn't have support for the type of image you're trying, for example tiff images.

To make it work, you need to add an extra jar to handle the image type.

You can add jai-imageio-core-1.3.1.jar to your classpath with:

    <!-- https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core -->
    <dependency>
        <groupId>com.github.jai-imageio</groupId>
        <artifactId>jai-imageio-core</artifactId>
        <version>1.3.1</version>
    </dependency>

To add support for:

  • wbmp
  • bmp
  • pcx
  • pnm
  • raw
  • tiff
  • gif (write)

You can check the list of supported formats with:

     for(String format : ImageIO.getReaderFormatNames())
        System.out.println(format);

Note that you only have to drop the jar (jai-imageio-core-1.3.1.jar for example) into your classpath to make it work.

Other projects that add additional support for image types include:

  • https://github.com/haraldk/TwelveMonkeys
  • https://github.com/geosolutions-it/imageio-ext