Partner – Microsoft – NPI (cat=Java)
announcement - icon

Microsoft JDConf 2024 conference is getting closer, on March 27th and 28th. Simply put, it's a free virtual event to learn about the newest developments in Java, Cloud, and AI.

Josh Long and Mark Heckler are kicking things off in the keynote, so it's definitely going to be both highly useful and quite practical.

This year’s theme is focused on developer productivity and how these technologies transform how we work, build, integrate, and modernize applications.

For the full conference agenda and speaker lineup, you can explore JDConf.com:

>> RSVP Now

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:

robot.createScreenCapture(rectangle);

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(
      Toolkit.getDefaultToolkit().getScreenSize());
    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.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!