java - 在java中组合图像

标签 java bufferedimage

这是我的代码:

    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/

相关文章:

java - 在 grails url 映射中使用目录

java - 在 Java 方法性能中使用 final 关键字?

java - XBee 双向通信(发送方和接收方)同时进行

java - Java 中 BufferedImage 的 3/3/2 RGB 样本字节数组

java - 如何控制图像的亮度?

java - JSP:如何将 HTML img 标签中的图像作为 blob 存储到数据库

java - 每当我在 Eclipse 中将浏览器设置为 DEFAULT WEB BROWSER(Chrome) 时,它都会显示错误。我该如何纠正它?

java - BufferedImage 实例数组 : IIOException

java - 使用 Java 裁剪图像的一部分并替换为另一部分

java - 实例化 BufferedImage 的步骤