如何在具有透明度的 java BufferedImage 中读取像素颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1599963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:35:46  来源:igfitidea点击:

How to read pixel color in a java BufferedImage with transparency

javatransparencybufferedimagejavax.imageio

提问by Richard H

I am reading pixel color in a BufferedImage as follows:

我正在读取 BufferedImage 中的像素颜色,如下所示:

.....
InputStream is = new BufferedInputStream(conn.getInputStream());
BufferedImage image = ImageIO.read(is);

int color = image.getRGB(x, y);

int  red = (colour & 0x00ff0000) >> 16;
int  green = (colour & 0x0000ff00) >> 8;
int  blue = colour & 0x000000ff;

Now this works fine except for png's with transparency. I find that if x,y refer to a transparent pixel with no color, i still read a color, generally the same color as used elsewhere in the image.

现在这工作正常,除了透明的 png。我发现如果 x,y 指的是一个没有颜色的透明像素,我仍然会读取一种颜色,通常与图像中其他地方使用的颜色相同。

How do I detect that the pixel is actually transparent and not colored?

如何检测像素实际上是透明的而不是彩色的?

Thanks

谢谢

采纳答案by jarnbjo

int alpha = (colour>>24) & 0xff;

The result is also a value ranging from 0 (completely transparent) to 255 (completely opaque).

结果也是一个范围从 0(完全透明)到 255(完全不透明)的值。