java - 尝试从 PNG 图像中提取字节

标签 java image png arrays bufferedimage

我正在尝试从 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/

相关文章:

mfc - Win32 : UpdateLayeredWindow failing sometimes (error 317)

c++ - 从 base64 C++ 解码和保存图像文件

java - JFileChooser - 不浏览 Windows Server 2008 机器中的 'Mounted Drives'

image - 只有 PNG 支持透明度,是这样吗?

swift - 'InfoKey' 不是 'UIImagePickerController' 的成员类型

python - GeoTIFF 在 PIL 中打开时出现问题

html - PNG图片在IE8中出现,在IE7中消失

java - 如何使 JFileChooser 在断开网络驱动器时正常运行?

java - 如何将 ListView 点击上的数据动态传递到另一个 Activity

java - 如何创建返回计算值的公共(public)计算函数?