【问题标题】:Byte array of 3/3/2 RGB samples to BufferedImage in Java3/3/2 RGB 样本的字节数组到 Java 中的 BufferedImage
【发布时间】:2017-12-06 23:06:07
【问题描述】:

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

【问题讨论】:

  • 为什么红色和绿色需要三位?通常的位掩码是“RRGGBBAA”(或“AARRGGBB”),其中“A”代表 alpha。
  • 我不需要 alpha 组件来达到我的目的。我构建了颜色模型:DirectColorModel model = new DirectColorModel(8, 0b00000000000000000000000011100000, 0b00000000000000000000000000011100, 0b00000000000000000000000000000011) 和缓冲区:DataBufferByte buffer = new DataBufferByte(data, data.length) 但后来我不知道如何构建光栅
  • 假设我有 RRGGBBAA 掩码,我将如何构造 BufferedImage?
  • 您可以简单地构建一个匹配的调色板并使用 IndexedColorModel

标签: java image awt bufferedimage


【解决方案1】:

首先,我们必须用您的数据创建一个数据缓冲区
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);
此外,您可以修剪二进制文字中的后续 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);
    }

我希望这会有所帮助!

【讨论】:

  • 谢谢,这会很有帮助!
猜你喜欢
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 2010-12-16
相关资源
最近更新 更多