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

时间:2017-11-12 19:46:01

标签: java image bit-manipulation pixel

如果

,我应该预期像素的颜色是黑色

image.getRGB(x, y)会返回0?

我的假设:我希望0,因为每个值(红色,绿色,蓝色)的位值都是零。我是否正确地想到这一点?

2 个答案:

答案 0 :(得分:2)

不,BufferedImage#getRGB()返回十六进制数。见本单元测试:

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

答案 1 :(得分:1)

"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

因此,当所有颜色组件都为零时,最终值不仅依赖于RGB:

AA000000

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