这是我的代码:
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();
}
我的问题是代码会输出这个图像:
我需要的是为图像提供白色背景。谢谢!
答案 0 :(得分:3)
这对我来说很危险:
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对象中的rect,这样就可以解释为什么背景不是白色的。为什么不只是创建一个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);
答案 1 :(得分:2)
在添加图像之前,绘制一个与图像大小相同的白色矩形:
g.clearRect(0,0, 486, 151);
g.setColor(Color.white);
g.fillRect(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();