如何使用 image.getRGB(x, y) 检查像素是否为黑色

How to check if a pixel is black using image.getRGB(x, y)

如果

我是否应该期望像素的颜色为黑色

image.getRGB(x, y) returns 0?

我的假设: 我期望为 0,因为每个值(红色、绿色、蓝色)的位值为零。我这样想对吗?

"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)."

也就是说,包装(十六进制位置)如下,其中每个组件的值可以为 0 (0x00) .. 255 (0xFF)。

AARRGGBB

因此,当所有 color 分量均为零时,最终值 不仅 取决于 RGB:

AA000000

事实上,AA 默认为 0xFF(“100% 不透明”),除非它在支持 alpha 的缓冲区/模型中明确设置为不同的值频道。

否,BufferedImage#getRGB() returns 十六进制数。查看此单元测试:

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);
  }
}