如何在Java中创建图像

dor*_*thy 5 java javax.imageio

在我的程序中说,我有这个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

jon*_*ins 5

图像中的背景为黑色,因为除了矩形中的像素之外,您没有为任何像素指定值。从每个像素的 RGB 为 (0, 0, 0)开始BufferedImage,即黑色。要为整个图像提供白色背景,只需用白色填充图像的整个矩形即可。

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 );
        ....        
}
Run Code Online (Sandbox Code Playgroud)

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