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
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
search for java byte array image
to find several similar questions answered.
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).
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.
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
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();
}