Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
leonardo Avatar asked Sep 10 '14 09:09

leonardo


People also ask

What does getRGB return?

getRGB. Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data. Color conversion takes place if the default model does not match the image ColorModel .

How do you find the RGB value of each pixel?

Retrieving the pixel contents (ARGB values) of an image −Get the pixel value at every point using the getRGB() method. Instantiate the Color object by passing the pixel value as a parameter. Get the Red, Green, Blue values using the getRed(), getGreen() and getBlue() methods respectively.


1 Answers

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:

               2          1          0 bitpos      32109876 54321098 76543210 ------   --+--------+--------+--------+ bits     ..|RRRRRRRR|GGGGGGGG|BBBBBBBB| 

You can extract or set the components using bitmasks:

int color = img.getRGB(x, y);  // Components will be in the range of 0..255: int blue = color & 0xff; int green = (color & 0xff00) >> 8; int red = (color & 0xff0000) >> 16; 

If the color also has an alpha component (transparency) ARGB, it gets the last remaining 8 bits.

           3          2          1          0 bitpos    10987654 32109876 54321098 76543210 ------   +--------+--------+--------+--------+ bits     |AAAAAAAA|RRRRRRRR|GGGGGGGG|BBBBBBBB| 

And the value:

int alpha = (color & 0xff000000) >>> 24; // Note the >>> shift                                          // required due to sign bit 

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:

blue : 240         // Strong blue green:  85         // A little green mixed in red  :   0         // No red component at all alpha: 255         // Completely opaque 
like image 115
icza Avatar answered Sep 21 '22 23:09

icza