How to convert array of bytes into Image in Java SE

后端 未结 5 1359
悲&欢浪女
悲&欢浪女 2020-12-09 23:07

What is the right way to convert raw array of bytes into Image in Java SE. array consist of bytes, where each three bytes represent one pixel, with each byte for correspondi

5条回答
  •  被撕碎了的回忆
    2020-12-09 23:24

    There is a setRGB variant which accepts an int array of RGBA values:

    BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int[] raw = new int[data.length * 4 / 3];
    for (int i = 0; i < data.length / 3; i++) {
        raw[i] = 0xFF000000 | 
            ((data[3 * i + 0] & 0xFF) << 16) |
            ((data[3 * i + 1] & 0xFF) << 8) |
            ((data[3 * i + 2] & 0xFF));
    }
    img.setRGB(0, 0, width, height, raw, 0, width);
    

    The performance characteristics is similar to CoderTao's solution.

提交回复
热议问题