如何在 JFrame 上保存图像

2022-01-24 00:00:00 image java swing jframe

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

I am working on a white board project and I encountered a problem when implementing the Save function.

这是我如何实现绘图功能

Here is how I implement the draw function

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

I am using JFileChooser for the file dialog

            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 上绘制的内容保存为图像?

There is no method like Frame.getImage() for JFrame, I am wondering how can I save what I draw on the JFrame as an image ?

推荐答案

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

You need to paint the frame's content to a BufferedImage first. Try something like...

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 传递给它.

Once you have that, you can use the ImageIO.write method, passing the img to it.

更新

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

So, I did a really quick test...

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

I started out with this background image...

​​

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

Which I loaded into my frame and laid a JLabel ontop

然后保存到文件中……

一切正常.

这是我使用的代码.

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

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

Without an example of the work flow, it's going to be tough to work out where you're going wrong.

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

I should note that I use printAll over paint because I've had issues with doing this using paint recently (throwing exceptions and the like)

相关文章