【问题标题】:Trying to extract the bytes from a PNG image尝试从 PNG 图像中提取字节
【发布时间】:2013-01-22 03:27:34
【问题描述】:

我正在尝试从 PNG 中提取字节并得到一些看起来很奇怪的结果。

这是我提取字节的方法:

public static byte[] extractBytes (String ImageName) throws IOException {
     // open image
     File imgPath = new File(ImageName);
     BufferedImage bufferedImage = ImageIO.read(imgPath);

     // get DataBufferBytes from Raster
     WritableRaster raster = bufferedImage.getRaster();
     DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

     return ( data.getData() );
}

这里是我调用函数并遍历生成的字节[]:

byte[] bytes = extractBytes("colorstrip.png");

for (int x : bytes) {
    System.out.println(x);
}

我一直在一个 4x1 图像上测试此代码,该图像按顺序包含一个红色像素、一个蓝色像素、一个绿色像素和一个紫色像素。这是输出:

-1
0
0
-1
-1
0
-1
0
-1
-1
0
0
-1
-1
0
-1

这个输出对我来说看起来不正确。我相信输出应该是这样的(我将 alpha 通道留空):

255
0
0

0
255
0

0
0
255

255
0
255

知道问题出在哪里吗?

【问题讨论】:

    标签: java image png bytearray bufferedimage


    【解决方案1】:

    Java 字节是有符号的,所以当您期望 255 在 0-255 范围内时,Java 使用的是 -128 到 127 范围,因此将无符号 255 打印为有符号 -1。

    【讨论】:

      【解决方案2】:

      BufferedImage 的类型是什么?我怀疑它是 TYPE_4BYTE_ABGR。 由于值 255 的字节在 Java 中将变为 -1,因此输出似乎是正确的。 -1, 0, 0, -1 = alpha:255,蓝色:0,绿色:0,红色 255。

      【讨论】:

      • +1 用于记住(除了已签名的 Java 字节)BufferedImage 支持严格的内部表示,不应假设。
      猜你喜欢
      • 2012-06-21
      • 2021-01-08
      • 2022-08-21
      • 2016-04-06
      • 2019-04-23
      • 2013-01-09
      • 1970-01-01
      • 2010-09-15
      相关资源
      最近更新 更多