gpt4 book ai didi

java - 如何在 Java 中创建图像

转载 作者:搜寻专家 更新时间:2023-11-01 02:26:52 25 4
gpt4 key购买 nike

在我的程序中说,我有这个 paint() 方法。我的愿望是创建绘制的矩形图像(使用 for 循环)。我尝试了下面的方法,它确实给了我那些矩形(蓝色),但背景全是黑色。当我运行程序而不创建图像时,只是在 JFrame 上绘制矩形,背景是白色的。我怎样才能解决这个问题。 ?

public void paint(Graphics g) {     
super.paint(g);
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
g = Image.getGraphics(); <<<----- is this correct?
g.setColor(Color.blue);
for ( ..... ) {
g.fillRect(X , Y, width , height);
....
}
try {
ImageIO.write(image, "jpg", new File("CustomImage.jpg"));
}catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

图像中的背景是黑色的,因为除了矩形中的像素外,您没有给任何像素赋值。 BufferedImage 开始时每个像素的 RGB 值为 (0, 0, 0),即黑色。要给整个图像一个白色背景,只需用白色填充整个图像矩形即可。

BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
g = image.createGraphics(); // not sure on this line, but this seems more right
g.setColor(Color.white);
g.fillRect(0, 0, 100, 100); // give the whole image a white background
g.setColor(Color.blue);
for( ..... ){
g.fillRect(X , Y, width , height );
....
}

请注意,我的回答是将图像写入具有白色背景的文件,而不是绘制到具有黑色背景的 JFrame。我不完全确定你想要哪一个。

关于java - 如何在 Java 中创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20425507/

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