Convert byte array of data type TYPE_4BYTE_ABGR to BufferedImage

前端 未结 2 1394
说谎
说谎 2021-01-25 10:38

I have a byte array with type TYPE_4BYTE_ABGR, and I know its width and height, I want to change it to BufferedImage, any ideas?

2条回答
  •  梦谈多话
    2021-01-25 11:17

    Might not be very efficient, but a BufferedImage can be converted to another type this way:

    public static BufferedImage convertToType(BufferedImage image, int type) {
        BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), type);
        Graphics2D graphics = newImage.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();
        return newImage;
    }
    

    About the method you want to be implemented, you would have to know the width or height of the image to convert a byte[] to a BufferedImage.

    Edit:
    One way is converting the byte[] to int[] (data type TYPE_INT_ARGB) and using setRGB:

    int[] dst = new int[width * height];
    for (int i = 0, j = 0; i < dst.length; i++) {
        int a = src[j++] & 0xff;
        int b = src[j++] & 0xff;
        int g = src[j++] & 0xff;
        int r = src[j++] & 0xff;
        dst[i] = (a << 24) | (r << 16) | (g << 8) | b;
    }
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    image.setRGB(0, 0, width, height, dst, 0, width);
    

提交回复
热议问题