14

Hi i want to convert panel which contains components like label and buttons to image file.

I have done the following code. The image was saved. but the content of the panel not visible or saved. Can anyone tell me how to save the panel with its components.

Code:

package PanelToImage;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class sample extends JPanel {

public JPanel firstpanel;
public JPanel secondpanel;
JLabel label1, label2;
JButton button1, button2;

public sample() {
    firstpanel = new JPanel();
    firstpanel.setSize(400,300); 
    firstpanel.setBackground(Color.RED);
    secondpanel = new JPanel();
    secondpanel.setBackground(Color.GREEN);
    secondpanel.setSize(400,300); 

    label1 = new JLabel("label1");
    label2 = new JLabel("label2");
    button1 = new JButton("button1");
    button2 = new JButton("button2");

    firstpanel.add(label1);
    firstpanel.add(button1);

    secondpanel.add(label2);
    secondpanel.add(button2);

    saveImage(firstpanel);

    add(firstpanel);

    // add(secondpanel);
}

public static void main(String args[]) {

    JFrame frame = new JFrame();
    sample sam = new sample();
    frame.setContentPane(sam);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);

}

private void saveImage(JPanel panel) {
    BufferedImage img = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
    panel.paint(img.getGraphics());
    try {
        ImageIO.write(img, "png", new File("E://Screen.png"));
        System.out.println("panel saved as image");

    } catch (Exception e) {
        System.out.println("panel not saved" + e.getMessage());
    }
}
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Babu R
  • 1,025
  • 8
  • 20
  • 40
  • See [ComponentImageCapture.java](http://stackoverflow.com/a/5853992/418556) for displaying visible components - scroll down for **See also** & A class by Rob Camick that takes a lot of the grunt work out of taking an image from a component that has not been displayed. And some of the other tricks for rendering components prior to display can be seen in [Why does the JTable header not appear in the image?](http://stackoverflow.com/q/7369814/418556) – Andrew Thompson Jun 30 '12 at 14:51
  • 1
    Seems to me you are providing the wrong `Path` for the file to be created. Since your Program doesn't know anything about what is `Drive E`, so the new `File` which will be created must be referenced with `Relative Path` with respect to the `.class File`, like `..\..\E:\Screen.png`, making it go two levels up and then reaching out for `Drive E`, something like this will work. The Image so created with my answer or @Alberto 's answer is created next to the .class file. – nIcE cOw Jun 30 '12 at 19:12

2 Answers2

20

Tthis code works for me (in the JFrame):

Container c = getContentPane();
BufferedImage im = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
c.paint(im.getGraphics());
ImageIO.write(im, "PNG", new File("shot.png"));

Maybe you have used custom panels. If true, try to add super.paint(g) at the beginning of the paint methods of your panels.

EDIT: You have to call saveImage after display the frame:

public static void main(String args[]) {
    ...
    frame.setSize(400, 300);
    sam.saveImage(sam.firstpanel);
}

EDIT 2: This is the saved image (is little because the layout, but is the proof that it should work):

enter image description here

I called the saveImage as last call in the main, and used a file in the user dir (new File("Screen.png")) as nIcE cOw said.

Community
  • 1
  • 1
Alberto
  • 1,569
  • 1
  • 22
  • 41
  • i am not using paint method. i m just using panel and add components with it. But the components not visible while saving panel into image. – Babu R Jun 30 '12 at 10:07
  • See my edit. You have to call saveImage after the frame is displayed. – Alberto Jun 30 '12 at 10:53
  • See [ComponentImageCapture.java](http://stackoverflow.com/a/5853992/418556) for displaying visible components - scroll down for **See also** & A class by Rob Camick that takes a lot of the grunt work out of taking an image from a component that has not been displayed. And some of the other tricks for rendering components prior to display can be seen in [Why does the JTable header not appear in the image?](http://stackoverflow.com/q/7369814/418556) – Andrew Thompson Jun 30 '12 at 14:53
  • sorry i cant convert panel to image with components.problem not solved. – Babu R Jun 30 '12 at 15:47
  • But have you tried to call `saveImage` after `setVisible`? It works? – Alberto Jun 30 '12 at 16:11
6

Here try this example program, instead of using getGraphics() seems like you have to use createGraphics() for the BufferedImage you are about to make.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SnapshotExample
{
    private JPanel contentPane;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Snapshot Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        JLabel label = new JLabel("This JLabel will display"
                        + " itself on the SNAPSHOT", JLabel.CENTER);
        contentPane.add(label);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        makePanelImage(contentPane);
    }

    private void makePanelImage(Component panel)
    {
        Dimension size = panel.getSize();
        BufferedImage image = new BufferedImage(
                    size.width, size.height 
                              , BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        panel.paint(g2);
        try
        {
            ImageIO.write(image, "png", new File("snapshot.png"));
            System.out.println("Panel saved as Image.");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {           
                new SnapshotExample().displayGUI();
            }
        });
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • See [ComponentImageCapture.java](http://stackoverflow.com/a/5853992/418556) for displaying visible components - scroll down for **See also** & A class by Rob Camick that takes a lot of the grunt work out of taking an image from a component that has not been displayed. And some of the other tricks for rendering components prior to display can be seen in [Why does the JTable header not appear in the image?](http://stackoverflow.com/q/7369814/418556) – Andrew Thompson Jun 30 '12 at 14:53
  • @AndrewThompson : Thankyou for these valuable links, I had seen that last question, once before when I just started learning `Painting in Swing`, though that whole thingy went over my head at that time. But this time hoping I be able to learn loads from these examples :-). Thankx again. Cheers – nIcE cOw Jun 30 '12 at 16:25