8

So I've been trying to export an image that I've drawn on a JPanel into an image. I've been using this method:

BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
paint(g);
try { ImageIO.write(image, "png", new File([location goes here]); } catch (IOException e) {}

I get an image in my intended location but I get a compressed version of what my JPanel shows. The same happens if I try to export a BMP as well. Is there a way to get a pixel-perfect image exported from the JPanel? Thanks in advance.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
user2589692
  • 83
  • 1
  • 3

2 Answers2

11

The panel needs to be laid out based on it's requirements. If the panel hasn't being realized on the screen yet, it may not render the way you expect it do

The following example assumes that the panel has not being displayed on the screen...

setSize(getPreferredSize());
BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
printAll(g);
g.dispose();
try { 
    ImageIO.write(image, "png", new File([location goes here]); 
} catch (IOException e) {
    e.printStackTrace();
}

You should avoid calling paint yourself, it can throw an exception if the component has not being realized on the screen, instead, use printAll

Also, if your create a resource, you should dispose of it ;)

Updated

I did this quick example. Screen shoot on top, jpeg on left, png on right.

jpeg is 30kb and png is 320kb

enter image description here

I used this to create it...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class PaintComponent {

    public static void main(String[] args) {
        new PaintComponent();
    }

    public PaintComponent() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPanel paintPane;

        public TestPane() {

            paintPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            paintPane.add(new JLabel("I'm a label"), gbc);
            paintPane.add(new JTextField("I'm a text field", 20), gbc);
            paintPane.add(new JLabel(new ImageIcon("some\pretty\picture")), gbc);

            setLayout(new BorderLayout());
            add(paintPane);

            JButton paint = new JButton("Capture");
            paint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    BufferedImage image = new BufferedImage(paintPane.getWidth(), paintPane.getHeight(), BufferedImage.TYPE_INT_RGB);
                    Graphics2D g = image.createGraphics();
                    paintPane.printAll(g);
                    g.dispose();
                    try {
                        ImageIO.write(image, "jpg", new File("Paint.jpg"));
                        ImageIO.write(image, "png", new File("Paint.png"));
                    } catch (IOException exp) {
                        exp.printStackTrace();
                    }
                }
            });
            add(paint, BorderLayout.SOUTH);

        }
    }
}

I would make sure that you are actually looking at the correct files ;)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks for the advice. My JPanel is being displayed on the screen when I export the image, though. Also, no matter what format I export the image in, they are all the same size (in terms of memory). Is that expected? – user2589692 Jul 17 '13 at 05:03
  • I would think it's not unexpected. Is the image what you are expecting? – MadProgrammer Jul 17 '13 at 05:08
  • Yeah it is, it's just not at the same quality of the image displayed in the JPanel. – user2589692 Jul 18 '13 at 03:58
  • Does it work with all the contents of a JPanel? For example, if a have a JLabel, a JButton and another JPanel, will all of them be printed? – Jas Apr 21 '17 at 03:41
  • @Jas If you invoke `printAll` on the parent component, then yes, it will print all the children and their children – MadProgrammer Apr 21 '17 at 03:42
2

If you are trying to make an image of a panel that is not visible on a window then check out Screen Image. It will invoke doLayout() on the panel to make sure the components are displayed properly.

camickr
  • 321,443
  • 19
  • 166
  • 288