62

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

VGR
  • 40,506
  • 4
  • 48
  • 63
Señor Reginold Francis
  • 16,318
  • 16
  • 57
  • 73

5 Answers5

98
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
bluish
  • 26,356
  • 27
  • 122
  • 180
Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • 10
    This doesn't answer the question, the question was for writing to an image file. This answer is for reading FROM an image file. Whats with all the up-votes? – Supercreature Dec 25 '15 at 15:50
  • 10
    The title says that, but the question says they have a byte array and need an Image, that's what this does. – Nick Veys Jan 29 '16 at 18:49
26

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);
}
Sam Barnum
  • 10,559
  • 3
  • 54
  • 60
5
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);
Usman
  • 1,116
  • 11
  • 13
2

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
  • 7,483
  • 3
  • 28
  • 33
1

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
  • 45,269
  • 12
  • 110
  • 134