Screen Capture in Java

In this post, I will be sharing how to screen capture in java using API. We will use java.awt.Robot class object to capture the coordinate system. Based on the coordinates we will construct the output image.

Read Also: How to Open Web Page in Java

Steps for Screen Capture in Java


1. Create an object of the Robot class to get the coordinate system of the primary screen.

2. We get the dimension of the primary screen by using Toolkit.getDefaultToolkit().getScreenSize() method. In other words, it returns the size of the screen.

3. We are passing the screenSize to the constructor of the Rectangle class. It constructs a new Rectangle whose top left corner is (0,0) and the Dimension argument specifies the height and width.

4. robot.createScreenCapture(screenRectangle) method creates an image containing pixels read from the screen.

5. ImageIO.write() method writes an image using an arbitrary ImageWriter that supports the given format to a File. It returns the static boolean value.

Java Program for Screen Capture

 import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.AWTException;
public class ScreenCaptureExample {
  public static void main(String args[]) {
    try {    
        Robot robot = new Robot();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        BufferedImage capture = robot.createScreenCapture(screenRectangle);
        File file = new File("screen-capture-demo.jpeg");
        boolean isCaptured = ImageIO.write(capture, "jpeg", file);
        System.out.println("Is ScreenCaptured? "+isCaptured+ " File path is: "+file.getAbsolutePath());
    }
    catch(IOException | AWTException e) {
        System.err.println(e);
    }
  }
}


Output:
Is ScreenCaptured? true
File path is: C:\Users\SubhamMittal\eclipse-workspace\Blog\screen-capture-demo.jpeg


screen capture demo in java


That's all for today. Please mention in the comments in case you have any questions related to the Screen Capture in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry