2016-02-29 18 views
-1

我挣扎了一下,试图了解如何有效地使用Java图像对象。显示到图形用户界面和保存到磁盘与单个对象/变量

我有一个非常简单的程序,它绘制一个图像,然后将该图像保存到磁盘。

public class myBrain { 

    public static void main(String[] args) { 

     JFrame lv_frame = new JFrame(); 
     lv_frame.setTitle("Drawing"); 
     lv_frame.setSize(300, 300); 
     lv_frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE); 

     lv_frame.add(new image()); 

     lv_frame.setVisible(true); 

    } 

} 

class image extends JPanel { 

    public void paintComponent(Graphics graphic) { 

     super.paintComponent(graphic); 

     // draw image to gui 

     Graphics2D graphic2D = (Graphics2D) graphic; 
     graphic2D.fillArc(0, 0, 250, 250, 0, 90); 

     // save image to disk 

     BufferedImage image = new BufferedImage(250, 250, BufferedImage.TYPE_4BYTE_ABGR_PRE); 

     graphic2D = image.createGraphics(); 
     graphic2D.fillArc(0, 0, 250, 250, 0, 90); 

     try { 
     File output = new File("file.png"); 
     ImageIO.write(image, "png", output); 
     } catch(IOException log) { 
     System.out.println(log); 
     } 

    } 

} 

在代码中有两个函数(我已经写他们在一个单一的功能,便于理解的目的)。一个处理gui和一个处理储蓄。

第一个是它的Graphics2D对象,它绘制的弧线很好。

第二个需要一个BufferedImage,这样我可以保存它,但是当我尝试为BufferedImage(image.createGraphics();)创建图形时,它会覆盖之前在Graphic2D上绘制的图形,这意味着我必须然后再次绘制(fillArc(0,0,250,250,0,90);)。

有没有办法解决这个问题,我不需要再次绘制图像来保存图像?

+2

不是你的问题的原因,但从来没有从任何组件的绘画方法(如paintComponent)中做文件I/O。该方法应该用于绘制组件并仅绘制组件。另外不要忘记打电话给超级方法。 –

+0

我知道,一旦我有一个工作版本,我将从绘画方法中删除它。离开超级方法是一个错误,我将它添加回 – Trent

+1

,所以你每隔几个小时一遍又一遍地做同样的问题... http://stackoverflow.com/questions/35696758/java-passing-2d -graphic-as-a-parameter/35697773#35697773 – gpasch

回答

1

你应该在你的BufferedImage开始绘画,留住它(作为一个类的成员,例如),然后在paintComponent方法得出BufferedImagegraphics2D.drawImage(...))。

保存方法应该保存相同的BufferedImage

+0

这听起来像它可以解决我的问题,虽然我不清楚如何实现它,您是否能够更新我的问题中的代码,以反映您的建议? – Trent