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?
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 RGB (i.e. Red, Green, Blue) components of that value use Color class. e.g.
Then you can get Red, Green, or Blue value by using
getRed()
,getGreen()
,getBlue()
,getAlpha()
. Then anint
value will be returned by these methods in familiar format having value0 < value < 255
If you don't wants to use
Color
class then you will need to use bitwise operations to get its value.Actually,You can transform the int to binary string by Integer.toBinaryString(-16755216),which is 11111111000000000101010111110000.it made up of 4 bytes: alpha, red, green, blue. The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components. The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue. Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution. Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF.
The RGB
int
color contains the Red, Green, Blue components of the color in its bits. You have to look at its binary or hexadecimal representation and not look at it as a whole integer number (not look at its decimal representation).An
int
has 32 bits, 3x8 = 24 is used to store the RGB components (8 bits for each) in the following format:You can extract or set the components using bitmasks:
If the color also has an alpha component (transparency) ARGB, it gets the last remaining 8 bits.
And the value:
An alpha value of 255 means that a color is completely opaque and a value of 0 means that the color is completely transparent.
Your color:
Your color is
color = -16755216
which has:It's explained in the docs:
So you get 8 bits alpha channel, 8 bits red, 8 bits green, 8 bits blue.
A simple (and slow way) to examine the value is to use
new java.awt.Color(colour, true);
and then call the getters.Or you can print the value as an unsigned 32bit hex value:
Integer.toString(colour, 16)
. Each two characters of the output will be one part of the ARGB set.See the implementation of
ColorModel.getRgb
: