在"缓冲图像"上绘制时,RGB颜色在包含alpha时发生变化



我正在尝试写入缓冲图像并读取其颜色。尽管alpha保持不变,但RGB颜色似乎发生了变化。我无法理解这背后的原因。如有任何帮助,我们将不胜感激。我需要图像返回与我所写的完全相同的颜色。

try {
BufferedImage img=new BufferedImage(256, 256,
BufferedImage.TYPE_INT_ARGB);
Graphics graphics =
img.createGraphics();
int r=45;int g=45; int b=100; int a=50;
System.out.println("Red  "+r+"   Green "+g+"    Blue "+b+"   alpha "+a);
graphics.setColor(new Color(r,g,b,a));
graphics.fillRect(10,10, 40, 40);
Integer i=img.getRGB(23,23);
Color c=new Color(i,true);
System.out.println("Going to read color back");
System.out.println("Red  "+c.getRed()+"   Green "+c.getGreen()+"    Blue "+c.getBlue()+"   alpha "+c.getAlpha());
} catch (Exception e) {
e.printStackTrace();
}

程序输出:红色45绿色45蓝色100阿尔法50

将读取彩色背

红色46绿色46蓝色102阿尔法50

如果你想保护源颜色,在用alpha在图像中绘制任何东西之前,应该添加以下代码。这解决了我的问题。

graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));

Alpha复合文档Alpha Composite教程

最新更新