Capture the Screen with Java’s Robot Class

Java’s Robot class makes it really easy to capture the screen as an image. Here, we’ll take a screenshot using the dimensions of the user’s screen resolution, show the image in a JFrame, and save it to disk as a GIF.

The Code

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SimpleScreenCapture {

	/**
	 * @param args
	 */
	public static void main( String[] args ) throws Exception {

		// Make a rectangle according to the size of the screen

		Rectangle rectangle = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );

		// Initialize a JFrame where we will show the image

		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

		// Take the screenshot

		Robot robot = new Robot();
		BufferedImage img = robot.createScreenCapture( rectangle );

		// Use a JLabel icon to display the image

		frame.add( new JLabel( new ImageIcon( img ) ) );
		frame.pack();
		frame.setVisible( true );

		// Save the image as a GIF to disk

		File file = new File( "screenshot.gif" );
		ImageIO.write( img, "gif", file );

	}

}
This entry was posted in Java and tagged , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

2 Trackbacks

  1. By Kurtis Chiappone | Saving a BufferedImage to Disk on December 30, 2010 at 3:51 am

    [...] I showed you how to take a screenshot and display it in a JFrame using Java’s Robot class. What if you wanted to save the image to [...]

  2. By Kurtis Chiappone | Screen Capture Utility on December 30, 2010 at 3:53 am

    [...] my previous posts on how to take a screenshot and how to save an image to disk, I’ve created a Screen Capture Utility extending these basic [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>