leonardo leonardo - 1 year ago 138
Java Question

Understanding BufferedImage.getRGB output values

I'm getting an integer value for the pixel in an image using this method:

int colour = img.getRGB(x, y);

Then I'm printing out the values and I see that black pixels correspond to a value like "-16777216", a kind of blue to something like "-16755216", etc. Can someone please explain me the logic behind this value?

Answer Source

getRGB(int x, int y) return you the value of color pixel at location (x,y).
You are misinterpreting the returned value.
It is in the binary format. like 11...11010101 and that is given to you as int value.
If you want to get its value use Color class. e.g.

Color mycolor = new Color(img.getRGB(x, y));

Then you can get red, green, or blue value by using getRed(), getGreen(), getBlue().
Then an int value will be returned by these methods in familiar format having value 0 < value < 225

int red = mycolor.getRed();

If you don't wants to use Color class then you will need to use bitwise operations to get its value.