1. 程式人生 > >Java 實現截屏

Java 實現截屏

direct created led png public span eight 目錄名 art

操作系統: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.

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

技術分享圖片

截取的圖片:

技術分享圖片

Java 實現截屏