我需要在旧图像上绘制新图像。我首先在BufferedImage中打开了两个图像,并将其白色背景更改为透明。然后我从旧图像的bufferedImage获得了一个Graphics2D对象,并调用了Graphics2D类的drawImage方法。然后我将旧图像保存到磁盘。当我打开保存的图像时,我发现只有白色背景的旧图像变为透明。任何人都可以告诉我我的代码有什么错误,或者如何解决我的错误?
BufferedImage newImage = ImageIO.read(new File("new.png"));
BufferedImage oldImage = ImageIO.read(new File("old.png"));
newImage = makeWhiteTransparent(newImage);
oldImage = makeWhiteTransparent(oldImage);
Graphics2D graphics = (Graphics2D) oldImage.getGraphics();
graphics.drawImage(newImage,null, 0,0);
File outputImage = new File("merged.png");
ImageIO.write(oldImage, "png", outputImage);
我的makeWhiteTransparent方法是这样的:
public static BufferedImage makeWhiteTransparent(BufferedImage img){
BufferedImage dst = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
dst.getGraphics().drawImage(img, 0, 0, null);
int markerRGB = Color.WHITE.getRGB() | 0xFF000000;
int width = dst.getWidth();
int height = dst.getHeight();
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
int rgb = dst.getRGB(x, y);
if ( ( rgb | 0xFF000000 ) == markerRGB ) {
int value = 0x00FFFFFF & rgb;
dst.setRGB(x, y, value);
}
}
}
return dst;
}
我尝试将graphics.drawImage(newImage,null,0,0)更改为graphics.drawImage(newImage,0,0,null),并按照建议将TYPE_4BYTE_ABGR更改为TYPE_INT_ARGB,但它什么也没做。错误仍然存在。
答案 0 :(得分:1)
这需要改变:
graphics.drawImage(newImage,null, 0,0);
到
graphics.drawImage(newImage, 0,0, null);
您使用的是错误版本的drawImage - 请检查http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html
-
还将类型TYPE_4BYTE_ABGR更改为TYPE_INT_ARGB
-
以下是它对我有用的方法:
public BufferedImage makeWhiteTransparent(BufferedImage img){
BufferedImage dst = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
dst.getGraphics().drawImage(img, 0, 0, null);
int markerRGB = 0x00ffffff; // Color.WHITE.getRGB() | 0xFF000000;
int width = dst.getWidth();
int height = dst.getHeight();
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
int rgb = dst.getRGB(x, y)&0x00ffffff;
if ( rgb == markerRGB ) {
int value = 0x00FFFFFF & rgb;
dst.setRGB(x, y, value);
}
}
}
return dst;
}
bim = makeWhiteTransparent(bim);
bim2 = makeWhiteTransparent(bim2);
Graphics2D graphics = (Graphics2D) bim.getGraphics();
graphics.drawImage(bim2,0,0, null);
g2.drawImage(bim, w/2-wc/2, h/2-hc/2, null);
答案 1 :(得分:0)
我最终得到了我的问题的答案。我所要做的就是创建一个新的BufferedImage并在其上绘制两个图像。下面是按预期工作的代码:
BufferedImage newImage = ImageIO.read(new File("new.png"));
BufferedImage oldImage = ImageIO.read(new File("old.png"));
oldImage = makeWhiteTransparent(oldImage);
newImage = makeWhiteTransparent(newImage);
int width = Math.max(newImage.getWidth(), oldImage.getWidth());
int height = Math.max(newImage.getHeight(), oldImage.getHeight());
BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = combined.getGraphics();
graphics.drawImage(oldImage, 0, 0, null);
graphics.drawImage(newImage, 0, 0, null);
File outputImage = new File("merged.png");
ImageIO.write(combined, "PNG", outputImage);