views:

350

answers:

5

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

+1  A: 

See http://stackoverflow.com/questions/1212882/convert-byte-array-to-image-in-java-without-knowing-the-type

search for java byte array image to find several similar questions answered.

lavinio
your answer wasnt very helpful as that wasnt exacly what I was looking for.
Steven1350
A: 

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).

Platinum Azure
A: 

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.

Kevin Loney
+2  A: 

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

Nick Veys
A: 

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);
} finally {
    if (out != null) out.close();
}
Sam Barnum