Java 实现截屏

操作系统:Windows 10 x64

参考:https://blog.csdn.net/weixin_40657079/article/details/83961708

 1 import java.awt.AWTException;
 2 import java.awt.Desktop;
 3 import java.awt.Dimension;
 4 import java.awt.Rectangle;
 5 import java.awt.Robot;
 6 import java.awt.Toolkit;
 7 import java.awt.image.BufferedImage;
 8 import java.io.File;
 9 import java.io.IOException;
10 import java.text.DateFormat;
11 import java.text.SimpleDateFormat;
12 import java.util.Date;
13 
14 import javax.imageio.ImageIO;
15 
16 public class Main {
17 
18     public static void main(String[] args) throws AWTException, IOException {
19         // 获取屏幕的尺寸
20         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
21         System.out.println("The width and the height of the screen is " + screenSize.getWidth() + " x " + screenSize.getHeight());
22         
23         // 截取屏幕
24         BufferedImage image = new Robot().createScreenCapture(new Rectangle(screenSize));
25         
26         // 设置日期格式,作为目录名
27         DateFormat dfDirectory = new SimpleDateFormat("yyyyMMdd");
28         // 创建一个用于保存图片的文件夹
29         File screenCaptureDirectory = new File("J:" + File.separator + "ScreenCapture" + File.separator + dfDirectory.format(new Date()));
30         if (!screenCaptureDirectory.exists()) {
31             screenCaptureDirectory.mkdirs();
32             System.out.println("The directory " + screenCaptureDirectory.getName() + " are Created.");
33         }
34         
35         // 设置日期格式,作为图片名
36         DateFormat dfImageName = new SimpleDateFormat("yyyyMMddhhmmss");
37         // 指定路径,并以特定的日期格式作为图片的名称
38         File imageFile = new File(screenCaptureDirectory, (dfImageName.format(new Date()) + ".png"));
39         
40         // 以指定的格式将截取的屏幕写到指定的文件
41         ImageIO.write(image, "png", imageFile);
42         
43         // 自动打开图片(没看懂!)
44         if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
45             Desktop.getDesktop().open(imageFile);
46         }
47     }
48 }

控制台输出的信息:

The width and the height of the screen is 1920.0 x 1080.0
The directory 20190504 are Created.

 

新创建的文件夹,以及截取的图片:

截取的图片:

猜你喜欢

转载自www.cnblogs.com/Satu/p/10807740.html
今日推荐