If I want to check if a pixel is black image.getRGB(x, y) will equal 0 right? [java]

This may be a simple question but I can't find anything to confirm my hypothesis.

Should I expect the color of the pixel to be black if

image.getRGB(x, y) returns 0?

I would expect 0 because the bit values of each of the values (Red, Green, Blue) would be zero. Am I correct in thinking this?

2 answers

  • answered 2017-11-12 19:54 user2864740

    "Returns the RGB value representing the color in the default sRGB ColorModel. (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are =blue)."

    That is, the packing (in hex locations) is as follows, where each component can have a value of 0 (0x00) .. 255 (0xFF).

    AARRGGBB
    

    Thus, the final value is not only dependent upon RGB, when all color components are zero:

    AA000000
    

    In fact, AA will be 0xFF ("100% opaque") by default unless it has explicitly been set to a different value in a buffer / model that supports an alpha channel.

  • answered 2017-11-12 20:01 Bedla

    No, BufferedImage#getRGB() returns hex number. See this unit test:

    public class TestRgb {
      @Test
      public void testBlack(){
        BufferedImage bufferedImage = new BufferedImage(1,1, TYPE_BYTE_BINARY);
        Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setPaint(new Color(0,0,0)); //black
        graphics2D.fillRect(0,0,1,1);
    
        // pass - alpha channel set by default, even on all black pixels
        TestCase.assertTrue(bufferedImage.getRGB(0,0)==0xFF000000);
    
        // pass - when looking at just the color values (last 24 bits) the value is 0
        TestCase.assertTrue((bufferedImage.getRGB(0,0) & 0x00FFFFFF)==0);
    
        // fail - see above
        TestCase.assertTrue(bufferedImage.getRGB(0,0)==0);
      }
    }