How to capture screenshot in Java

We need use java.awt and javax.imageio packages for this program.

package com.startwithjava;
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;
 
/**
 * This program demonstrates how to capture a screenshot (full screen)
 * as an image which will be saved into a file.
 * @author www.expertwebindia.com
 *
 */
public class ScreeshotTest {
    public static void main(String[] arr) {
        try {
            Robot robot = new Robot();
            String format = "jpg";
            String fileName = "Screenshot." + format;
            //To capture fullscreen we are using Rectangle object 
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
            ImageIO.write(screenFullImage, format, new File(fileName));
            System.out.println("Screenshot saved!");
        } catch (AWTException | IOException ex) {
            System.err.println(ex);
        }
    }
}

Leave a Reply