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

后端 未结 2 1465
难免孤独
难免孤独 2020-12-21 00:41

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 ret

相关标签:
2条回答
  • 2020-12-21 01:36
    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.

    0 讨论(0)
  • 2020-12-21 01:42

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

    0 讨论(0)
提交回复
热议问题