Search code examples
javaawtbufferedimage

Java: Saving canvas to an image file results in a blank image


I have a class that extends Canvas and implements the below methods. The problem is, that whenever I call exportImage, all I get is a blank white image. There should be drawings on the image.

/**
  * 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();
    }    
}

Solution

  • I used render instead of paint in the exportImage method to print the graphics to the image. Seems like it was a problem with the bufferStrategy I used.