Thursday, August 8, 2013

Take Screen Shot in Java





The following code shows you how to take a screenshot using java.The heart of this code is the Robot class. This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.
To use this class we need to import java.awt.Robot. In eclipse shift+ctrl+o will do all this import stuffs for you.

Here is the method to capture screen shot

/*
 * This method takes screen shot
 * @param filename is the file name of the screenshot
 */
 public static void captureScreen(String fileName) throws Exception {
   
                   //get the dimention (i.e. width & height in pixels) of the screen
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                   //Create a rectangular shape of size of the screen
     Rectangle screenRectangle = new Rectangle(screenSize);
                   //create a new robot object
     Robot robot = new Robot();
                   //take a snapshot of the screen
     BufferedImage image = robot.createScreenCapture(screenRectangle);
                   //write the image to file
     ImageIO.write(image, "jpg", new File(fileName));
   
 }

createScreenCapture(Rectangle screenRect)creates an image containing pixels read from the screen & returns it as a BufferedImage. You can change the image format from jpg to any other format you like.


For more info on Robot class visit oracle docs here


9 comments :