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

巧了我就是萌 提交于 2019-12-18 06:33:00

问题


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


回答1:


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




回答2:


Use Java Advanced Imaging to process JPEG2000 images.

Similar question: read jpeg2000 files in java




回答3:


ServletOutputStream out = response.getOutputStream();
out.write(user.getBytes());

The above is how its worked for me in the past where user has a profile picture simply stored in a byte array. The servlet realizes this and outputs the image.



来源:https://stackoverflow.com/questions/7119472/convert-byte-array-byte-to-image-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!