Convert Byte Array to BufferedImage in Java

Convert byte array to BufferedImage in java

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:

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 passing byte[] in the constructor.
  • Pass above InputStream to ImageIo.read() and get BufferedImage from it.

Output:

BufferedImage@5bfbf16f: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@150c158 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 500 height = 500 #numDataElements 3 dataOff[0] = 2

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

That’s all about how to convert byte array to BufferedImage in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *