Search code examples
javaimage-processingcolorsrgbbufferedimage

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?


Solution

  • 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.

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

    Then you can get the Red, Green, Blue, or Alpha values by using getRed(), getGreen(), getBlue(), getAlpha(). Then an int value will be returned by these methods in familiar format having value 0 < value < 255

    int red = mycolor.getRed();
    

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