Table of Contents
In this article, we will see how to convert byte array to BufferedImage in java.
💡 Outline
To convert byte array to BufferedImage, you can use below code:
1234 InputStream inputStream = new ByteArrayInputStream(byteArr); // byte[] byteArrBufferedImage bufferImage = ImageIO.read(inputStream);
Convert byte array image to BufferedImage in java
Using ByteArrayInputStream
Here are steps to convert byte array to BufferedImage
in java.
- Create
ByteArrayInputStream
object by passingbyte[]
in the constructor. - Pass above
InputStream
toImageIo.read()
and getBufferedImage
from it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package org.arpit.java2blog; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; public class ByteArrayToBufferedImageMain { public static void main(String[] args) throws IOException { Path source = Paths.get("MyFile.png"); BufferedImage bufferedImage = ImageIO.read(source.toFile()); byte[] byteArr = getByteArrayForImage(bufferedImage); BufferedImage bufferedImageNew = convertByteArrayToBufferedImage(byteArr); System.out.println(bufferedImageNew); } // convert byte[] to a BufferedImage public static BufferedImage convertByteArrayToBufferedImage(byte[] byteArr) throws IOException { InputStream is = new ByteArrayInputStream(byteArr); BufferedImage bufferedImage = ImageIO.read(is); return bufferedImage; } // Get byte array from input file public static byte[] getByteArrayForImage(BufferedImage bufferedImage) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); byte[] bytesArr = baos.toByteArray(); return bytesArr; } } |
Output:
Using BufferedImage’s setData
Above approach may not work in some case and may return null.
You can follow below steps to use this method as per this stackoverflow thread.
- Create a blank image
- Transform byte array to Raster and use setData to fill the image
1 2 3 4 5 6 7 8 9 |
// convert byte[] to a BufferedImage public static BufferedImage convertByteArrayToBufferedImage(byte[] byteArr) throws IOException { BufferedImage bufferedImage=new BufferedImage(10, 10, BufferedImage.TYPE_INT_BGR); Raster raster = Raster.createRaster(bufferedImage.getSampleModel(), new DataBufferByte(byteArr, byteArr.length), new Point()); bufferedImage.setData( raster); return bufferedImage; } |
That’s all about how to convert byte array to BufferedImage in java.