我在尝试复制BufferedImage
对象时遇到了问题。
我使用drawImage (BufferedImage image, int x, int y, ImageObserver observer)
方法将原始图像绘制到新图像上,并为每个图像设置BufferedImage.TYPE_INT_ARGB
,但是当我打印新图像颜色的值时,RGBA值略有不同。
我需要复制原始图像,因为我有一个JPanel
持有要作为背景绘制的图像。在我的应用程序的其他部分中,我必须从面板获取图像,但我希望返回一个副本以避免图像被其他地方修改。
如何解决这个问题?
代码:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class BufferedImageColorBug
{
public static void main (String [] a) {
Color [] colors = {
new Color (202,230,186,14),
new Color (254,65,188,214),
new Color (247,104,197,198),
new Color (158,93,79,239),
new Color (235,45,57,194),
new Color (155,77,126,150),
new Color (164,237,20,172),
new Color (184,106,97,191),
new Color (187,249,135,85),
new Color (236,112,98,24)
};
BufferedImage image = new BufferedImage (colors.length, 1, BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < colors.length; x ++) image.setRGB (x, 0, colors [x].getRGB ());
BufferedImage copy = new BufferedImage (image.getWidth (), image.getHeight (), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = copy.createGraphics ();
g2d.drawImage (image, 0, 0, null);
g2d.dispose ();
for (int x = 0; x < colors.length; x ++) {
Color color = new Color (copy.getRGB (x, 0), true);
System.out.println (color.getRed () + "," + color.getGreen () + "," + color.getBlue () + "," + color.getAlpha ());
}
}
}
这是我的输出结果:
200,237,182,14
254,66,188,214
247,104,197,198
158,93,79,239
235,45,57,194
155,76,126,150
165,237,19,172
184,105,97,191
186,249,135,85
234,117,96,24
编辑
我谈论克隆图像是因为这是我的目的,但是我想要理解为什么不同图像的rgba值是不同的。
我已经尝试使用BufferedImage.TYPE_INT_ARGB_PRE
,但没有帮助。