2012-09-16 93 views
0

我有一個擴展了Canvas的類並實現了以下方法。問題是,每當我打電話給exportImage時,我所得到的只是一張空白的圖像。圖像上應該有圖紙。Java:將畫布保存爲圖像文件會產生空白圖像

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

爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

0

我在exportImage方法使用render代替paint將圖形打印到圖像上。似乎這是我用過的bufferStrategy的問題。

0

我簡化您的paint方法是如下那樣簡單和出口工作正常。不過,我建議你重寫paintComponent而不是paint

public void paint(Graphics g) { 
    g.setColor(Color.BLUE); 
    g.drawRect(10, 10, getWidth() - 20, getHeight() - 20); 
} 
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(); 
    }  

}

+0

當我使用'paint'時,保存的圖像完全是黑色,而不是畫布中的圖像。 –