gpt4 book ai didi

java - 在java中组合图像

转载 作者:行者123 更新时间:2023-11-30 06:33:54 25 4
gpt4 key购买 nike

这是我的代码:

    Image partNumberImage = Toolkit.getDefaultToolkit().getImage("D:/partNumber.png");
Image lotNumberImage = Toolkit.getDefaultToolkit().getImage("D:/lotNumber.png");
Image dteImage = Toolkit.getDefaultToolkit().getImage("D:/dte.png");
Image quantityImage = Toolkit.getDefaultToolkit().getImage("D:/quantity.png");

BufferedImage combinedImage = new BufferedImage(486,
151,
BufferedImage.TYPE_INT_RGB);


Graphics g = combinedImage.getGraphics();

combinedImage.createGraphics().setBackground(Color.white);

g.clearRect(0,0, 486, 151);
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);


g.dispose();

Iterator writers = ImageIO.getImageWritersByFormatName("png");
ImageWriter writer = (ImageWriter) writers.next();
if (writer == null) {
throw new RuntimeException("PNG not supported?!");
}

ImageOutputStream out = ImageIO.createImageOutputStream(
new File("D:/Combined.png" ));
writer.setOutput(out);
writer.write(combinedImage);
out.close();
}

我的问题是代码会输出这张图片:

enter image description here

我需要的是为图像设置白色背景。谢谢!

最佳答案

这对我来说有风险:

Graphics g = combinedImage.getGraphics(); // Graphics object #1

combinedImage.createGraphics().setBackground(Color.white); // Graphics object #2
// so now you've set the background color for the second Graphics object only

g.clearRect(0,0, 486, 151); // but clear the rect in the first Graphics object
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);

在我看来,您可能正在创建两个截然不同的 Graphics 对象,一个是 Graphics2D 对象,一个是 Graphics 对象。当您在 Graphics2D 对象中设置背景颜色时,您清除了 Graphics 对象中的一个矩形,因此它可以解释为什么您的背景不是白色。为什么不直接创建一个 Graphics2D 对象并将其用于所有用途:

Graphics2D g = combinedImage.createGraphics(); 
g.setBackground(Color.white);

// Now there is only one Graphics object, and its background has been set
g.clearRect(0,0, 486, 151); // This now uses the correct background color
g.drawImage(partNumberImage, x, 18, null);
g.drawImage(lotNumberImage, x, 48, null);
g.drawImage(dteImage, x, 58, null);
g.drawImage(quantityImage, x, 68, null);

关于java - 在java中组合图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7577325/

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