显示到GUI并保存到具有单个对象/变量的磁盘 [英] Display to GUI and Save to Disk with a Single Object/Variable

查看:105
本文介绍了显示到GUI并保存到具有单个对象/变量的磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在努力了解如何有效地使用Java图像对象方面有些挣扎.

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

   }

}

在代码中有两个函数(为了易于理解,我将它们写在一个函数中).一个来处理gui,另一个来处理保存.

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.

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

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

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

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?

推荐答案

您应该开始在BufferedImage上绘画,保留它(例如作为类成员),然后在paintComponent方法中画出BufferedImage( graphics2D.drawImage(...)).

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

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

The saving method should save the same BufferedImage.

这篇关于显示到GUI并保存到具有单个对象/变量的磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆