如何在Java中创建图像

8

在我的程序中,我有一个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();
    }
}

1
你应该使用JPanel并覆盖paintComponent而不是尝试在JFrame上进行绘制。像JFrame这样的顶级容器没有双缓冲,这可能会导致问题。 - Paul Samsotha
4个回答

5

在您的图像中,背景为黑色是因为除了矩形内的像素外,您没有为任何像素赋值。 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上进行绘制。我不确定你想要哪个方案。

3
BufferedImage bufferedImage = new BufferedImage(width, height, 
              BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bufferedImage.createGraphics();

Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);

RenderingHints rh = new RenderingHints(
       RenderingHints.KEY_ANTIALIASING,
       RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING, 
       RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);

GradientPaint gp = new GradientPaint(0, 0, 
Color.red, 0, height/2, Color.black, true);

g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);

g2d.setColor(new Color(255, 153, 0));

2

试试这个

public void paint(Graphics g) {     
  super.paint(g);
  BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
  g = Image.createGraphics();     // it should be createGraphics
  g.setBackground(Color.black);
  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();
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接