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 written 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();
        }
    }
}

How do I read image file?

Here you see a code sample to read an image file. This code will work either the image file is located in a file folder or inside a jar file. You can use javax.imageio.ImageIO class to read the image file.

package org.kodejava.example.awt;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class ReadingImage {
    public static void main(String[] args) {
        ReadingImage demo = new ReadingImage();
        demo.getImage();
    }

    public void getImage() {
        try {
            InputStream is = getClass().getResourceAsStream("/kodejava.png");
            BufferedImage image = ImageIO.read(is);

            // Do something with the image.
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}