Java:将画布保存到图像文件会产生空白图像

时间:2012-09-16 10:19:01

标签: java awt bufferedimage

我有一个扩展Canvas的类并实现以下方法。问题是,每当我拨打exportImage时,我得到的只是一张空白的白色图片。图像上应该有图纸。

/**
  * Paint the graphics
  */
public void paint(Graphics g) {
    rows = sim.sp.getRows();
    columns = sim.sp.getColumns();
    createBufferStrategy(1);
    // Use a bufferstrategy to remove that annoying flickering of the display
    // when rendering
    bf = getBufferStrategy();
    g = null;
    try{
        g = bf.getDrawGraphics();
        render(g);
    } finally {
        g.dispose();
    }
    bf.show();
    Toolkit.getDefaultToolkit().sync();    
}

/**
 * Render the cells in the frame with a neat border around each cell
 * @param g
 */
private Graphics render(Graphics g) {
    // Paint the simulation onto the graphics...

}

/**
  * Export the the display area to a file
  * @param imageName the image to save the file to
  */
public void exportImage(String imageName) {
    BufferedImage image = new  BufferedImage(getWidth(), getHeight(),BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = image.createGraphics();
    paintAll(graphics);
    graphics.dispose();
    try {
        System.out.println("Exporting image: "+imageName);
        FileOutputStream out = new FileOutputStream(imageName);
        ImageIO.write(image, "png", out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }    
}

3 个答案:

答案 0 :(得分:0)

我将您的paint方法简化为如下所示,并且导出工作正常。不过,我建议您覆盖paintComponent而不是paint

public void paint(Graphics g) {
    g.setColor(Color.BLUE);
    g.drawRect(10, 10, getWidth() - 20, getHeight() - 20);
}

答案 1 :(得分:0)

尝试使用paint方法,而不是paintAll

public void exportImage(String imageName) {
    BufferedImage image = new  BufferedImage(getWidth(), getHeight(),BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = image.createGraphics();
    paint(graphics);
    graphics.dispose();
    try {
        System.out.println("Exporting image: "+imageName);
        FileOutputStream out = new FileOutputStream(imageName);
        ImageIO.write(image, "png", out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }    

}

答案 2 :(得分:0)

我在render方法中使用paint代替exportImage来将图形打印到图像。似乎这是我使用的bufferStrategy的问题。

相关问题