How do I create a screen capture using Robot class?

In this example you’ll see how to create a screen capture / screenshot and save it as an image file such a PNG image. Some classes are use in this program including the java.awt.Robot, java.awt.image.BufferedImage and javax.imageio.ImageIO.

package org.kodejava.example.awt;

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

public class ScreenCapture {
    public static void main(String[] args) {
        try {
            Robot robot = new Robot();

            //
            // Capture screen from the top left in 200 by 200 pixel size.
            //
            BufferedImage bufferedImage = robot.createScreenCapture(
                    new Rectangle(new Dimension(200, 200)));

            //
            // The captured image will the writen into a file called
            // screenshot.png
            //
            File imageFile = new File("screenshot.png");
            ImageIO.write(bufferedImage, "png", imageFile);
        } catch (AWTException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply