Monday, August 16, 2010

How to capture screen shot of current window using Java

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

Key points to be used :
  1. Create Object of Class Robot
  2. Decide size of window to be captured
  3. Call robot.createScreenCapture to capture image

Java Program to capture screenshot of current Window :

package com.anuj.basic;

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

public class ScreenShots {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ScreenShots shots = new ScreenShots();
        try {
            shots.captureScreen("CapturedImage.png");
            System.out.println("Screen shots created successfully");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // take screen shots of current window
    public void captureScreen(String fileName) throws Exception {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        ImageIO.write(image, "png", new File(fileName));

    }
}

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/