我将 JPanel
的背景颜色设置为白色。但是,当我将其保存为 JPG 或其他图像格式时,背景是黑色的。我已输入此代码 TYPE_INT_ARGB
但它不起作用。如何将背景设置为其他颜色?例如蓝色、白色等
public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
// Create a buffered image in which to draw
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// Create a graphics contents on the buffered image
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1)); // set the thickness of polygon line
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.00f));
g2d.setPaint(Color.black);//color of the polygon line
g2d.setBackground(Color.WHITE);
//draw polygon
for (Polygon triangle : triangles)
g2d.drawPolygon(triangle);
try {
File file = new File("newimage.jpg");
ImageIO.write(bufferedImage, "jpg", file);
} catch (IOException e) {
}
}//public void paint(Graphics g)
最佳答案
我确实意识到这是一个非常古老的问题,但我自己也遇到了类似的问题,因为我找到了答案(在 javadocs 中),所以我想无论如何我都会将其发布在这里。
当您在图形对象上设置背景颜色时,只有在清除区域时才会发挥作用。因此,只需立即清除整个区域,您就会拥有您喜欢的颜色的背景:
graphics.clearRect(0, 0, width, height);
关于java - 当我将图像另存为 JPG 时,为什么会出现黑色背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1576359/