我正在尝试从 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[] 的地方:
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 channel 留空):
255
0
0
0
255
0
0
0
255
255
0
255
知道问题出在哪里吗?
最佳答案
Java 字节是有符号的,因此当您期望 0-255 范围内的 255 时,java 使用的是 -128 到 127 范围,因此将无符号 255 打印为有符号 -1。
关于java - 尝试从 PNG 图像中提取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14451096/