gpt4 book ai didi

java - 在旧图像上绘制新图像java

转载 作者:行者123 更新时间:2023-12-01 09:56:11 25 4
gpt4 key购买 nike

我需要在旧图像上绘制新图像。我首先在 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,但没有执行任何操作。错误仍然存​​在。

最佳答案

需要更改:

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);

关于java - 在旧图像上绘制新图像java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37194702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com