I just announced the new Spring 5 modules in REST With Spring:


1. Overview

When you need to perform a print screen action on your desktop, there is an built-in ‘PrntScr’ button on the keyboard to help you with it. Sometimes that’s enough.

But the issue arises when you need to do that action programmatically. Simply put, you may need to save a current screenshot as an image file using Java.

Let’s have a look how we can do that.

2. The Robot Class

Java java.awt.Robot class is the main API we’re going to be using. This call contains a method called ‘createScreenCapture‘ which takes a screenshot when a specific shape is passed:


As the above method returns a java.awt.image.BufferedImage instance, all you have to do is to write the retrieved image to a file using the javax.imageio.ImageIO utility class.

3. Capturing and Saving the Image File

The Java code for image capturing and saving is as follows:

public void getScreenshot(int timeToWait) throws Exception {
    Rectangle rec = new Rectangle(
    Robot robot = new Robot();
    BufferedImage img = robot.createScreenCapture(rectangle);
    ImageIO.write(img, "jpg", setupFileNamePath());

Here, it is possible to capture a part of the screen by setting the required size to the java.awt.Rectangle instance. However, in the above example, it has been set to capture the full screen, by setting the current screen size.

4. Conclusion

In this tutorial, we had a quick look on the usage of a print screen in Java. The source code of the examples above can be found in the GitHub project.

I just announced the new Spring 5 modules in REST With Spring: