在此示例中,您将看到如何创建屏幕截图/屏幕截图并将其另存为图像文件(例如PNG图像)。有些类是在这个方案包括使用java.awt.Robot,java.awt.image.BufferedImage和javax.imageio.ImageIO。
package org.nhooo.example.awt; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.AWTException; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.io.File; import java.io.IOException; public class ScreenCapture { public static void main(String[] args) { try { Robot robot = new Robot(); // 从左上方以200 x 200像素的尺寸捕获屏幕。 BufferedImage bufferedImage = robot.createScreenCapture( new Rectangle(new Dimension(200, 200))); // 捕获的图像将被写入一个名为 // screenshot.png File imageFile = new File("screenshot.png"); ImageIO.write(bufferedImage, "png", imageFile); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }