0

我有一个绘图程序,允许用户绘制线条、框、文本甚至 JPEG。

我希望能够保存用户绘制的图像,但是对于如何将用户的创作转换为我可以轻松使用的格式(图像或 BufferedImage)我有点困惑。

用户在 JPanel 上绘制他们的内容(我们称之为 JPanel inputPanel)。如果用户单击一个按钮(让我们将此按钮称为 saveButton)。弹出一个 JFileChooser 询问将其保存到哪里,然后 BAM,保存创建(我已经知道如何以编程方式保存图像)。

有没有一种简单的方法可以以这种方式将 JPanel 转换为 Image 或 BufferedImage?

谷歌搜索/搜索 StackOverFlow 仅提供使用 setIcon() 将图像绘制到 JPanel 上的解决方案,这无济于事。

4

1 回答 1

5

小例子如何做到这一点:

public class Example
{
    public static void main ( String[] args )
    {
        JPanel panel = new JPanel ( new FlowLayout () )
        {
            protected void paintComponent ( Graphics g )
            {
                super.paintComponent ( g );
                g.setColor ( Color.BLACK );
                g.drawLine ( 0, 0, getWidth (), getHeight () );
            }
        };
        panel.add ( new JLabel ( "label" ) );
        panel.add ( new JButton ( "button" ) );
        panel.add ( new JCheckBox ( "check" ) );


        JFrame frame = new JFrame (  );
        frame.add ( panel );
        frame.pack ();
        frame.setVisible ( true );

        BufferedImage bi = new BufferedImage ( panel.getWidth (), panel.getHeight (), BufferedImage.TYPE_INT_ARGB );
        Graphics2D g2d = bi.createGraphics ();
        panel.paintAll ( g2d );
        g2d.dispose ();

        try
        {
            ImageIO.write ( bi, "png", new File ( "C:\\image.png" ) );
        }
        catch ( IOException e )
        {
            e.printStackTrace ();
        }

        System.exit ( 0 );
    }
}

在面板上放置或绘制的所有内容都将保存到 BufferedImage 中,然后保存到指定位置的 image.png 文件中。

请注意,面板必须显示(必须在某些帧上实际可见)才能绘制到图像上,否则您将获得空白图像。

于 2013-08-15T10:50:47.387 回答