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

问题描述 投票:0回答:4

我有一个扩展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();
    }    
}
java awt bufferedimage
4个回答
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
投票

我在render方法中使用paint而不是exportImage将图形打印到图像。好像是我使用的bufferStrategy有问题。


0
投票

我在绘制的画布上使用了此方法。除了我在画布上绘制的图像外,图像还保存了面板上的所有内容。有什么想法吗?

© www.soinside.com 2019 - 2024. All rights reserved.