Convert byte array (byte[]) to Image in Java

crocky picture crocky · Aug 19, 2011 · Viewed 30.5k times · Source

I have a byte[] that I want to convert to an Image and display the image in a label. The byte[] is of a jpeg 2000 format. I have tried the code below but it returns null:

InputStream in = new ByteArrayInputStream(bytearray);
BufferedImage image = ImageIO.read(in);

The image value comes back as null.

I want to be able to display the image in a label like below:

jLabel.setIcon(new ImageIcon(image));

Thanks

Answer

ctype.h picture ctype.h · Oct 1, 2012

To convert an array of bytes, i.e. byte[] into an Image, use getImage(). Probably the easiest way to do this is to instantiate an ImageIcon using the ImageIcon(byte[]) constructor, and then call getImage(). This is illustrated in the method below, particularly the last line:

public Image createImage(){
   //ccurve.png
   byte[] b = {-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82,
      0, 0, 0, 15, 0, 0, 0, 15, 8, 6, 0, 0, 0, 59, -42, -107,
      74, 0, 0, 0, 64, 73, 68, 65, 84, 120, -38, 99, 96, -64, 14, -2,
      99, -63, 68, 1, 100, -59, -1, -79, -120, 17, -44, -8, 31, -121, 28, 81,
      26, -1, -29, 113, 13, 78, -51, 100, -125, -1, -108, 24, 64, 86, -24, -30,
      11, 101, -6, -37, 76, -106, -97, 25, 104, 17, 96, -76, 77, 97, 20, -89,
      109, -110, 114, 21, 0, -82, -127, 56, -56, 56, 76, -17, -42, 0, 0, 0,
      0, 73, 69, 78, 68, -82, 66, 96, -126};
   return new ImageIcon(b).getImage();
}

I think this can by used for png, gif, bmp, and jpg images. Also the byte array does not have to be hard-coded, as in this example.

If you want an ImageIcon instead of an Image, don't call getImage():

public ImageIcon createImageIcon(){
   //ccurve.png
   byte[] b = {-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82,
      0, 0, 0, 15, 0, 0, 0, 15, 8, 6, 0, 0, 0, 59, -42, -107,
      74, 0, 0, 0, 64, 73, 68, 65, 84, 120, -38, 99, 96, -64, 14, -2,
      99, -63, 68, 1, 100, -59, -1, -79, -120, 17, -44, -8, 31, -121, 28, 81,
      26, -1, -29, 113, 13, 78, -51, 100, -125, -1, -108, 24, 64, 86, -24, -30,
      11, 101, -6, -37, 76, -106, -97, 25, 104, 17, 96, -76, 77, 97, 20, -89,
      109, -110, 114, 21, 0, -82, -127, 56, -56, 56, 76, -17, -42, 0, 0, 0,
      0, 73, 69, 78, 68, -82, 66, 96, -126};
   return new ImageIcon(b);
}

Then you can call jlabel.setIcon(createIconImage());.