How do I create a screen capture using Robot class?

John Doe ·

1094 Views

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.Robotjava.awt.image.BufferedImage and javax.imageio.ImageIO.

package org.kodejava.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 written into a file called
            // screenshot.png
            File imageFile = new File("screenshot.png");
            ImageIO.write(bufferedImage, "png", imageFile);
        } catch (AWTException | IOException e) {
            e.printStackTrace();
        }
    }
}

https://kodejava.org/how-do-i-create-a-screen-capture-using-robot-class/

BufferedImage ImageIO Robot