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 are " + 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() + " is 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 are 1920.0 x 1080.0
The directory 20190504 is created.

 

 

新創建的文件夾,以及截取的圖片:

 

截取的圖片:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM