Saturday, 8 June 2013

Capture the Screen with Java’s Robot Class

While surfing through internet, I came to this amazing piece of code in Java that takes the screen shot of your desktop and save it in a PNG file.
This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation.
Copy and paste following code in your Java class and invoke the method captureScreen() with file name as argument. The screen shot will be stored in the file that you specified in argument.

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 {
public static void main(String[] args) throws Exception {
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
frame.add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setVisible(true);
File file = new File("screenshot.gif");

ImageIO.write(img, "gif", file);
}
}

No comments: