将绘制的图片保存在文件[java]中的JPanel上

时间:2015-07-31 10:58:08

标签: java swing graphics jpanel png

我已经制作了一个代码来绘制Jpanel

frame1.add( new JPanel() {
    public void paintComponent( Graphics g ) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(Color.white);
        g2.fillRect(0, 0, width, height);
        //Drawnig Part
});
  • 一切都很好
  • 现在,我的问题是如何将我在JPanel上绘制的内容保存在文件a.PNG或任何其他类型中
  • 我花了很多时间来编写Drawing Part,因此如果您可以通过更改代码的必需部分来建议解决方案,而不是重写整个代码,将会很有帮助。

2 个答案:

答案 0 :(得分:1)

我建议您使用BufferedImage缓冲绘图操作,如下所示:

// This should not be done in the draw method, but rather when
// the frame is created. You should also make a new buffer image when
// the frame is resized. `frameWidth` and `frameHeight` are the
// frame's dimensions.
BufferedImage bufferImage = new BufferedImage(frameWidth, frameHeight,
            BufferedImage.TYPE_INT_ARGB);
Graphics2D bufferGraphics = bufferImage.createGraphics();


// In your draw method, do the following steps:

// 1. Clear the buffer:
bufferGraphics.clearRect(0, 0, width, height);

// 2. Draw things to bufferGraphics...

// 3. Copy the buffer:
g2.drawImage(bufferImage, null, 0, 0);

// When you want to save your image presented in the frame, call the following:
ImageIO.write(bufferImage, "png", new File("frameImage.png"));
如果您需要更多信息,

The Java Tutorial on Creating and Drawing to an Image以及ImageIO API reference可能会有所帮助。

答案 1 :(得分:0)

请查看Writing/Saving an Image以获取更多详细信息,但基本上您可以执行类似...

的操作
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
// Draw what ever you want to to the graphics context
g2d.dispose();

ImageIO.write(img, "png", new File("My Awesome Drawing.png"));

如果您无法将绘图逻辑与面板分开,则可以使用Graphics中的BufferedImage上下文来绘制组件。

查看Exporting a JPanel to an imagePrint the whole program layout示例