package Jietu; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class CameraTest { private String filePreStr; // 默認前綴(選擇存儲路徑例如: D:\\) private String defName = "cameraImg"; // 默認截圖名稱 static int serialNum = 0; //截圖名稱後面的數字累加 private String imageFormat; // 圖像文件的格式 private String defaultImageFormat = "png"; //截圖後綴 Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); //獲取全屏幕的寬高尺寸等數據 public CameraTest() { filePreStr = defName; imageFormat = defaultImageFormat; } public CameraTest(String s, String format) { filePreStr = s; imageFormat = format; } public void snapShot() { try { // *** 核心代碼 *** 拷貝屏幕到一個BufferedImage對象screenshot BufferedImage screenshot = (new Robot()).createScreenCapture(new Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight())); serialNum++; // 根據文件前綴變量和文件格式變量,自動生成文件名 String name = filePreStr + String.valueOf(serialNum) + "." + imageFormat; File f = new File(name); System.out.print("Save File " + name); // 將screenshot對象寫入圖像文件 ImageIO.write(screenshot, imageFormat, f); System.out.print("..Finished!\n"); } catch (Exception ex) { System.out.println(ex); } } // 運行以後,便可將全屏幕截圖保存到指定的目錄下面
// 配合前端頁面上面的選擇尺寸等邏輯,傳到後臺,便可實現自由選擇截圖區域和大小的截圖
public static void main(String[] args) { CameraTest cam = new CameraTest("d:\\Hello", "png");// cam.snapShot(); } }
以上代碼便可實現將全屏幕截圖保存到指定目錄下前端
核心代碼爲java
snapShot方法中的相關邏輯orm