【问题标题】:Byte array to an 8 bit truecolor image字节数组到 8 位真彩色图像
【发布时间】:2016-04-18 22:36:29
【问题描述】:

我正在尝试从旧 PC 游戏中提取一些精灵。我找到了这些精灵并将它们以灰度方式撕成单独的文件。现在我正在努力研究如何给它们上色。可执行文件或其数据文件中似乎没有任何调色板数据 - 这一点,再加上游戏所需的颜色深度(256 色)让我相信每个字节实际上是一个 8 位真彩色值。

假设我有一个(在这种情况下是缩短的)数组,看起来像这样:

12 11 12 11
0A 13 12 11
13 12 11 0A
12 11 13 13

一些类似于我用来编写图像的示例代码如下所示:

DataInputStream dis = new DataInputStream(new FileInputStream("GAME.EXE"));

dis.skipBytes(bytesToImage);

BufferedImage bufferedImage = new BufferedImage(columns, rows, BufferedImage.TYPE_BYTE_INDEXED);

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        byte pixel = dis.readByte();

        System.out.print(toHexString(pixel));

        //For now, greyscale everything.
        int value = pixel << 16 | pixel << 8 | pixel;

        bufferedImage.setRGB(j, i, value);
    }

    System.out.print(System.getProperty("line.separator"));
}

ImageIO.write(bufferedImage, "PNG", new File("test.png"));

我已经搞砸了传入构造函数的 imageType 和手动传入的 ColorModel,但似乎都没有做任何有用的事情。对像素进行二进制 AND 和一些位移操作主要只是将图像设置为深红色。

在这种情况下,如何将每个像素设置为正确的真彩色值?

【问题讨论】:

  • 我已经尝试过了 - 由于从字节转换 -> int 颜色值,一切都是蓝色的(只设置了低位)。
  • 是的,你是对的。文档说“8 位组件”,它的意思是它使用 8 位来存储 RGB,而不是每种颜色的 8 位。

标签: java image colors sprite


【解决方案1】:

8 位真彩色表示第 7 到 5 位包含红色,第 4 到 2 位包含绿色,第 1 和第 0 位包含蓝色。 (即RRRGGGBB)您需要将这些转移到 24 位真彩色模型中的高位。

对 RGB 颜色使用 24 位颜色模型,如 TYPE_INT_RGB 或 TYPE_INT_ARGB,并从 8 位值中导出 24 位像素值:

int pixel24 = 
    ((pixel & (128+64+32)) << (16+5-5)) |
    ((pixel & (16+8+4))    << (8+5-2))  |
    ((pixel & (2+1))       << 6);

换句话说:

int pixel24 = 
    ((pixel & 224) << 16) | ((pixel & 28) << 11) | ((pixel & 3) << 6);

或者

int pixel24 = 
    ((pixel & 0xE0) << 16) | ((pixel & 0x1C) << 11) | ((pixel & 0x03) << 6);

【讨论】:

  • 这实际上与最终工作的结果非常接近:int r = ((pixel &amp; 0xE0) &lt;&lt; 16); int g = ((pixel &amp; 0x1C) &lt;&lt; 11); int b = ((pixel &amp; 0x03) &lt;&lt; 6); bufferedImage.setRGB(j, i, r | g | b);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多