View RSS Feed

My Java Tips

Capture screenshots

Rate this Entry
by , 11-14-2011 at 06:41 PM (993 Views)
Taking screenshots in windows is simple and very useful in our day to day business. It is done by pressing the Print Screen key on your keyboard [PrtScn], pasting it in image editor such as MS paint and then editing and saving it. In this post, I will write about how to do this from Java program.


Java provides classes to help us which capturing screens.

java.awt.Robot is used to generate native system input events which can be used to for test automation, and other applications where control of the mouse and keyboard is needed. We will used Robot class to capture a rectangle area of the screen. We will use following method to read and capture pixels from the screen mentioned as rectangle.

Java Code:
BufferedImage createScreenCapture(Rectangle screenRect)
Also we will use javax.imageio.imageIO class for saving the image on the disk in the required format. We will be using the following method to write the image file on the disk:

Java Code:
static boolean write(RenderedImage im, String formatName, File output)
Time for demonstration:

Java Code:
try {
Robot robot = new Robot();
BufferedImage bi=robot.createScreenCapture(new Rectangle(400,600));
ImageIO.write(bi, "jpg", new File("C://screens//img1.jpg"));

} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
We mentioned the area to capture as rectangle. The images will be capture and will be stored as a jpeg file in the file system.

Happy coding!

Submit "Capture screenshots" to Facebook Submit "Capture screenshots" to Digg Submit "Capture screenshots" to del.icio.us Submit "Capture screenshots" to StumbleUpon Submit "Capture screenshots" to Google

Comments