【问题标题】:How to save a image on JFrame如何在 JFrame 上保存图像
【发布时间】:2013-06-26 17:15:22
【问题描述】:

我正在做一个白板项目,在实现保存功能时遇到了问题。

这是我如何实现绘图功能

Graphics2D g2d = (Graphics2D) frm.getGraphics();
g2d.setColor(Current_Color);
Line2D p2d = new Line2D.Double(StartPoint.getX(),StartPoint.getY(), e.getX() 
     + Xoffset, e.getY() + Yoffset);
g2d.setStroke(new BasicStroke(Integer.parseInt(choice_size.getSelectedItem())));
g2d.draw(p2d);

我在文件对话框中使用 JFileChooser

            int returnVal = saveFileChooser.showSaveDialog(frm);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File currentDir = saveFileChooser.getCurrentDirectory();
                String fileName = saveFileChooser.getSelectedFile()
                        .getName();
                String savePath = currentDir + "\\" + fileName + ".jpg";

                try {
                    ImageIO.write(<image>,<suffix>,<file>);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

对于 JFrame,没有像 Frame.getImage() 这样的方法,我想知道如何将我在 JFrame 上绘制的内容保存为图像?

【问题讨论】:

标签: java image swing jframe


【解决方案1】:

您需要先将框架的内容绘制到BufferedImage。尝试类似...

Container content = frm.getContentPane();
BufferedImage img = new BufferedImage(container.getWidth(), container.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();

content.printAll(g2d);

g2d.dispose();

一旦你有了它,你就可以使用ImageIO.write 方法,将img 传递给它。

更新

所以,我做了一个非常快速的测试......

我从这个背景图片开始...

我将其加载到我的框架中并在顶部放置了 JLabel

然后保存到文件中……

一切正常。

这是我使用的代码。

public class TestSaveFrame extends JFrame {

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }
                new TestSaveFrame();
            }
        });
    }

    public TestSaveFrame() {

        setTitle("Save me");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        BackgroundPane pane = new BackgroundPane();
        pane.setLayout(new GridBagLayout());

        JLabel label = new JLabel("I'm sitting on top");
        label.setFont(label.getFont().deriveFont(Font.BOLD, 24f));
        label.setForeground(Color.WHITE);

        pane.add(label);

        add(pane);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);

        pane.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
                    Container content = getContentPane();
                    BufferedImage img = new BufferedImage(content.getWidth(), content.getHeight(), BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2d = img.createGraphics();
                    content.printAll(g2d);
                    g2d.dispose();

                    try {
                        ImageIO.write(img, "png", new File("C:/PrintMe.png"));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

    }

    public class BackgroundPane extends JPanel {

        private Image background = null;

        public BackgroundPane() {
            try {
                background = ImageIO.read(getClass().getResource("/MT015.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return background == null ? new Dimension(200, 200) : new Dimension(background.getWidth(this), background.getHeight(this));
        }

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);
            if (background != null) {
                int x = (getWidth() - background.getWidth(this)) / 2;
                int y = (getHeight() - background.getHeight(this)) / 2;

                g.drawImage(background, x, y, this);
            }
        }
    }
}

如果没有工作流程示例,就很难找出哪里出错了。

我应该注意我使用 printAll 而不是 paint 因为我最近在使用 paint 时遇到了问题(抛出异常等)

【讨论】:

  • 是的,我之前试过,但是如果我在JFileChooser部分里面加上那个,我之前画的图片就会消失,也就是说无法获取JFrame上的当前内容。
  • 我在答案中添加了一个示例供您查看
  • 好像是在显示JFileChooser之前清除了内容?这是应用程序的一部分吗?对话框关闭后内容是否保留???如果是这种情况,您可能需要获取内容的副本(通过BufferedImage)并将其传递给保存方法
  • Container cont = frm.getContentPane(); BufferedImage image = new BufferedImage(cont.getWidth(),cont.getHeight(),BufferedImage.TYPE_INT_RGB); ImageIO.write(image, "png", new File(savePath));
  • 好的,第一条评论是,框架在屏幕上是否可见,是否已布局?
猜你喜欢
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
相关资源
最近更新 更多