Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save window contents as an image

Tags:

java

swing

I want to capture the contents of a JPanel as an image so that I can store it exactly as the user sees it. Is there a relatively simple way to do this with swing?

like image 639
Rocky Pulley Avatar asked Dec 21 '22 19:12

Rocky Pulley


1 Answers

From here http://forums.oracle.com/forums/thread.jspa?threadID=2156176&tstart=0

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SavePaint extends JPanel
{

    public SavePaint()
    {
        JFrame frame = new JFrame("TheFrame");
        frame.add(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.setVisible(true);

        try
        {
            BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = image.createGraphics();
            frame.paint(graphics2D);
            ImageIO.write(image,"jpeg", new File("/home/deniz/Desktop/jmemPractice.jpeg"));
        }
        catch(Exception exception)
        {
            //code
        }
    }

    protected void paintComponent(Graphics g)
    {
        g.drawRect(50,50,50,50);
    }

    public static void main(String[] args)
    {
        new SavePaint();
    }
}
like image 149
PeterMmm Avatar answered Dec 29 '22 01:12

PeterMmm