Reputation: 337
I'm trying to extract the bytes from a PNG and am getting some weird looking results.
Here is my extract byte method:
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() );
}
And here is where I call the function and loop through the resulting byte[]:
byte[] bytes = extractBytes("colorstrip.png");
for (int x : bytes) {
System.out.println(x);
}
I've been testing this code on a 4x1 image simply containing a red pixel, a blue pixel, a green pixel, and a purple pixel in that order. Here is the output:
-1
0
0
-1
-1
0
-1
0
-1
-1
0
0
-1
-1
0
-1
This output does not look correct to me. I believe the output should look something like this (I've left the alpha channels blank):
255
0
0
0
255
0
0
0
255
255
0
255
Any idea what the problem is?
Upvotes: 1
Views: 1312
Reputation: 8139
What is the type of the BufferedImage? I suspect it's TYPE_4BYTE_ABGR. Since a byte with value 255 would become -1 in Java, the output seems correct. -1, 0, 0, -1 = alpha: 255, blue: 0, green: 0, red 255.
Upvotes: 2
Reputation: 21793
Java bytes are signed, so when you'd expect 255 in a 0-255 range, java is using a -128 to 127 range and so prints unsigned 255 as signed -1.
Upvotes: 3