How to take screenshot programmatically in Java

How to take screenshot programmatically in Java

You may be surprised to know that by writing a few lines of code in JAVA , you can actually take a snapshot of your screen. In this tutorial, we are going to learn how to take screenshot programmatically in Java. You can not only take a screenshot but also can save it in the desired image file format like .png or .jpg.

The main class to capture a screen is java.awt.Robot. It provides a method called createScreenCapture which captures the current (active) screen. The method returns the captured image as a BufferedImage object which can be drawn onto a GUI component or saved to a file. We can use the ImageIO.write() method to save the captured image to a file.

Java program to capture full screen

To take a screenshot of the full screen, we need to know the screen size. The Toolkit.getDefaultToolkit().getScreenSize() method can be used to get the size of the screen.

The following Java program captures a full screen and saves it to a JPG image file format.

FullScreenCaptureExample.java

The image file (FullScreenshot.jpg) will be stored under the D directory. Note that the program captures the current active window. Hence if you run the program and stay in the same window, the image of that window only will be captured. That’s why in the code I have included Thread.sleep(5000) statement so that, before the program captures the screen, you can switch to other window for which you need the screenshot.

I have also added code to show a success pop-up (awt window) once the image is saved.

Java program to capture portion of a screen

If you only want to capture a portion of a screen, you need to specify the portion using a rectangular region. A rectangular region can be defined using coordinate points (X,Y) and its width, and its height. Here the rectangular area starts at the upper-left corner is at (X, Y) in the coordinate space. Java provides java.awt.Rectangle class to define a rectangular area.

PartialScreenCaptureExample.java

The above program captures an image of size 500 x 400 starting from the point (10, 50) in the coordinate space of the screen.

That’s all about taking a screenshot using Java program. If you have any doubts, post it in the comments section.

 

 

 

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.