How to Print Screen in Java – 如何在Java中打印屏幕

最后修改: 2016年 10月 30日


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.

当你需要在桌面上执行打印屏幕的操作时,键盘上有一个内置的 “PrntScr “按钮来帮助你完成。有时这就足够了。

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:

Java java.awt.Robot类是我们将要使用的主要API。这个调用包含了一个叫做’createScreenCapture‘的方法,当一个特定的形状被传递时,它就会拍摄一张屏幕。


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.