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

最后修改: 2016年 10月 30日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

但当你需要以编程方式进行这一操作时,问题就来了。简单地说,你可能需要用Java将当前的屏幕截图保存为一个图像文件。

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

让我们来看看我们如何能够做到这一点。

2. The Robot Class

2、机器人

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‘的方法,当一个特定的形状被传递时,它就会拍摄一张屏幕。

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.

由于上述方法返回一个java.awt.image.BufferedImage实例,你所要做的就是使用javax.imageio.ImageIO实用类将检索到的图像写入文件中。

3. Capturing and Saving the Image File

3.捕捉和保存图像文件

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

捕获和保存图像的Java代码如下。

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.

在这里,通过对java.awt.Rectangle实例设置所需的尺寸,可以捕获屏幕的一部分。然而,在上面的例子中,通过设置当前的屏幕尺寸,它已经被设置为捕获全屏。

4. Conclusion

4.结论

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.

在本教程中,我们快速了解了Java中打印屏幕的用法。上述例子的源代码可以在GitHub项目中找到。