Java 中 BufferedImage 的 3/3/2 RGB 样本的字节数组

Byte array of 3/3/2 RGB samples to BufferedImage in Java

我有一个字节数组,其中每个字节描述一个像素(256 种颜色)。这是我使用的位掩码: 0xRRRGGGBB 因此,R 和 G 分量有 3 位,B 分量有 2 位。 假设我知道图像的宽度和高度,如何从该数组构造 BufferedImage?

首先,我们必须用您的数据创建一个数据缓冲区
DataBufferByte buffer = new DataBufferByte(data, data.length);

接下来,我们需要声明 "bandMasks" 以便栅格能够理解您的格式
int[] bandMasks = {0b11100000, 0b00011100, 0b00000011};

现在,我们可以创建光栅
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, bandMasks, null); (仅供参考,宽度指定了两次,因为它是扫描尺寸)

现在我们可以使用缓冲区、光栅和颜色模型创建图像
BufferedImage image = new BufferedImage(new DirectColorModel(8, 0b11100000, 0b00011100, 0b00000011), raster, false, null);
此外,您可以 trim 关闭二进制文字中的后续 0,因为这些位默认为 0(0b00000011 与 0b11 相同或(十进制)00029 与 29 相同)您不需要指定整数中的所有 32 位

我使用整个片段验证了之前的代码是否有效:

    byte[] data = new byte[]{
        (byte) 0b00000011/*Blue*/, (byte) 0b11100011/*Purple*/,
        (byte) 0b11100011/*Purple*/, (byte) 0b11111111/*White*/};//This is the "image"

    int width = 2, height = 2;

    DataBufferByte buffer = new DataBufferByte(data, data.length);
    int[] bandMasks = {0b11100000, 0b00011100, 0b00000011};

    WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, bandMasks, null);

    BufferedImage image = new BufferedImage(new DirectColorModel(8, 0b11100000, 0b00011100, 0b00000011), raster, false, null);

    JFrame frame = new JFrame("Test");
    Canvas c = new Canvas();
    frame.add(c);
    frame.setSize(1440, 810);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    while (true) {
        Graphics g = c.getGraphics();
        g.drawImage(image, 0, 0, image.getWidth() * 40, image.getHeight() * 40, null);
    }

希望对您有所帮助!