Byte Array to Image object

JavaArraysImageByte

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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 - Java

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 - Java

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 - Java

According to the Java docs, it looks like you need to use http://java.sun.com/j2se/1.3/docs/api/java/awt/image/MemoryImageSource.html">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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeñor Reginold FrancisView Question on Stackoverflow
Solution 1 - JavaNick VeysView Answer on Stackoverflow
Solution 2 - JavaSam BarnumView Answer on Stackoverflow
Solution 3 - JavaUsmanView Answer on Stackoverflow
Solution 4 - JavaKevin LoneyView Answer on Stackoverflow
Solution 5 - JavaPlatinum AzureView Answer on Stackoverflow