简体   繁体   English

如何在JFrame上保存图像

[英]How to save a image on 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);

I am using JFileChooser for the file dialog 我正在使用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();
                }
            }

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 ? JFrame没有像Frame.getImage()这样的方法,我想知道如何将在JFrame上绘制的内容保存为图像?

You need to paint the frame's content to a BufferedImage first. 您需要先将框架的内容绘制到BufferedImage 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();

Once you have that, you can use the ImageIO.write method, passing the img to it. 一旦有了它,就可以使用ImageIO.write方法,将img传递给它。

UPDATE UPDATE

So, I did a really quick test... 所以,我做了一个非常快速的测试...

I started out with this background image... 我从这张背景图片开始...

背景

Which I loaded into my frame and laid a JLabel ontop 我将其加载到框架中并在其上放置了一个JLabel

帧

And then saved to a file... 然后保存到文件...

产量

All of which worked fine. 所有这些都很好。

This is the code that I used. 这是我使用的代码。

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. 如果没有工作流程的示例,很难弄清哪里出了问题。

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) 我应该注意,我使用printAll over paint是因为最近在使用paint进行printAll遇到了问题( printAll异常等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM