Byte Array to Image object

120,642

Solution 1

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

Solution 2

If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}

Solution 3

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

Solution 4

Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

Solution 5

According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).

Share:
120,642
Señor Reginold Francis
Author by

Señor Reginold Francis

Updated on December 07, 2020

Comments

  • Señor Reginold Francis
    Señor Reginold Francis over 3 years

    I am given a byte[] array in Java which contains the bytes for an image, and I need to output it into an image. How would I go about doing this?

    Much thanks