我终于明白了。尝试设置graphics.setComposite(AlphaComposite.Src)
。在我自己的库代码中,我这样做了,但我从未考虑过它......
因为默认的组合是AlphaComposite.SrcOver
,你实际上是构成半透明像素到完全透明像素,两者都具有非预乘 Alpha,因此这里存在差异。使用AlphaComposite.Src
你基本上说只有来源才重要。
另请注意,较低的 alpha 值意味着更透明。这意味着对于低 alpha,RGB 值的重要性较小,因为它们在合成时乘以 alpha(即17/255
对于您的示例图像),因此当合成到不透明背景上时,差异不会产生影响。
所以我会说:有些出乎意料?是的。可以接受吗?可能是。 :-)
这是代码的更新版本,使用AlphaComposite.Src
,以及没有差异的输出:
public static void main(String[] args) {
//it also happens with TYPE_INT_ARGB
BufferedImage bi1 = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
// rather arbitrary. low values of alpha tend to give more difference
int argb = 0x11663322;
bi1.setRGB(0, 0, argb);
int p1 = bi1.getRGB(0, 0);
BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
bi1.getType());
Graphics2D graphics = bi2.createGraphics();
try {
graphics.setComposite(AlphaComposite.Src);
graphics.drawImage(bi1, 0, 0, null);
}
finally {
graphics.dispose();
}
int p2 = bi2.getRGB(0, 0);
System.out.printf("im1: %08x %s ", p1, formatARGB(p1));
System.out.printf("im2: %08x %s %s\n", p2,
formatARGB(p2), (p1 == p2 ? "" : "DIF"));
}
public static String formatARGB(int v) {
return String.format("(%d,%d,%d,%d)",
(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF);
}
Output:
im1: 11663322 (17,102,51,34) im2: 11663322 (17,102,51,34)