Display to GUI and Save to Disk with a Single Object/Variable [duplicate]

早过忘川 提交于 2019-12-23 06:28:09

问题


I'm struggling a bit trying to understand how to effectively use java image objects.

I have a very simple program which draws an image and then saves that image to the disk.

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);
      }

   }

}

In the code there are two functions (I have written them in a single function for ease of understanding purposes). One to handle the gui and one to handle the saving.

The first one has it's Graphics2D object which it draws the arc to which is fine.

The second one needs a BufferedImage so that I can save it however when I try to create the graphic for the BufferedImage (image.createGraphics();) it overrides what I have drawn previously on the graphic2D which means I have to then draw it again (fillArc(0, 0, 250, 250, 0, 90);).

Is there a way around this so that I don't need to draw the image a second time to save it?


回答1:


You should start painting on your BufferedImage, retain it (as a class member for example), then in paintComponent method draw that BufferedImage (graphics2D.drawImage(...)).

The saving method should save the same BufferedImage.



来源:https://stackoverflow.com/questions/35702877/display-to-gui-and-save-to-disk-with-a-single-object-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!