0

I have a paint program that allows the user to draw lines, boxes, text, or even JPEGs.

I want to be able to save images the user draws, however I am a little confused about how to go about turning the user's creation into a format I can easily work with (Image or BufferedImage).

The user draws their content on a JPanel (let's call this JPanel inputPanel). If the user clicks a button (lets call this button saveButton). a JFileChooser pops up asking where to save it to, then BAM, the creation is saved (I know how to save an Image programatically already).

Is there an easy way to cast or convert a JPanel into an Image or BufferedImage in this way?

Googling/searching StackOverFlow only gives solutions to drawing an Image onto a JPanel using setIcon(), which doesn't help.

Josh Monks
  • 129
  • 1
  • 2
  • 9
  • create a BufferedImage from Xxx.getGraphics??? – mKorbel Aug 15 '13 at 10:45
  • 2
    Please have a look at this wonderful [answer](http://stackoverflow.com/a/5853992/1057230) by @AndrewThompson and a small [answer](http://stackoverflow.com/a/11274785/1057230) by me :-). For drawing on [JPanel or JLabel](http://stackoverflow.com/a/11372350/1057230) Hope it helps :-) – nIcE cOw Aug 15 '13 at 10:50
  • 1
    It seems you have little understanding how Java drawing actually works. Please look at [swing custom drawing tutorial](http://docs.oracle.com/javase/tutorial/uiswing/painting/) and work on the answer yourself. – Dariusz Aug 15 '13 at 10:54

1 Answers1

5

Small example how you can do that:

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

Everything that is placed or painted on the panel will be saved onto the BufferedImage and then saved into image.png file at the specified location.

Be aware that panel must be showing (must be actually visible on some frame) to paint onto the image, otherwise you will get empty image.

Mikle Garin
  • 10,083
  • 37
  • 59