Sunday, December 25, 2011

Screen Capture Using java

In this post I show how to capture screen with java.
Capture.java


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

public class MyScreenCapture {
    public static void main(String args[]) throws AWTException
    {
        Robot robot = new Robot();
        int width,height;
        width=(int) Toolkit.getDefaultToolkit().getScreenSize().getWidth(); // to get the screen width
        height=(int) Toolkit.getDefaultToolkit().getScreenSize().getHeight(); // to get the screen size
       
        BufferedImage bi=robot.createScreenCapture(new Rectangle(width, height));
        try {
            ImageIO.write(bi, "jpeg", new File(System.currentTimeMillis()+".jpeg"));
        } catch (IOException e) {
           
            e.printStackTrace();
        } 
    }   
}

In the above code createScreenCapture() method creates an image containing pixels read from the screen.
ImageIO.write() method writes an image using an arbitrary ImageWriter that supports the given format to a File.
Click here to know about Robot class.

No comments:

Post a Comment