Java 標準 API 中的 java.awt.Robot 類別提供了強大的螢幕截圖、滑鼠鍵盤模擬等功能。結合 BufferedImage、ImageIO 以及影像過濾器,可以輕鬆實作螢幕截圖、儲存檔案與區域裁剪功能。本文提供完整可執行的工具類實作。
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class ScreenCaptureUtil {
/**
* 擷取指定螢幕區域,回傳 BufferedImage
* @param x 左上角 X 座標
* @param y 左上角 Y 座標
* @param width 寬度
* @param height 高度
* @return 截圖 BufferedImage,失敗回傳 null
*/
public static BufferedImage captureScreen(int x, int y, int width, int height) {
try {
Robot robot = new Robot();
Rectangle rect = new Rectangle(x, y, width, height);
return robot.createScreenCapture(rect);
} catch (AWTException e) {
System.err.println("建立 Robot 失敗: " + e.getMessage());
return null;
}
}
/**
* 擷取螢幕區域並儲存為圖片檔案
* @param x 左上角 X 座標
* @param y 左上角 Y 座標
* @param width 寬度
* @param height 高度
* @param savePath 儲存目錄路徑
* @param fileName 檔案名稱(不含副檔名)
* @param format 圖片格式 (png, jpg, bmp 等)
* @return 是否儲存成功
*/
public static boolean captureScreenToFile(int x, int y, int width, int height,
String savePath, String fileName, String format) {
BufferedImage image = captureScreen(x, y, width, height);
if (image == null) return false;
try {
File dir = new File(savePath);
if (!dir.exists()) dir.mkdirs();
File file = new File(dir, fileName + "." + format.toLowerCase());
return ImageIO.write(image, format, file);
} catch (IOException e) {
System.err.println("儲存截圖失敗: " + e.getMessage());
return false;
}
}
/**
* 裁剪 BufferedImage 指定區域
* @param src 來源圖片
* @param x 裁剪區域左上角 X
* @param y 裁剪區域左上角 Y
* @param width 裁剪寬度
* @param height 裁剪高度
* @return 裁剪後的 BufferedImage
*/
public static BufferedImage cropImage(BufferedImage src, int x, int y, int width, int height) {
if (src == null) return null;
// 邊界檢查
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x + width > src.getWidth()) width = src.getWidth() - x;
if (y + height > src.getHeight()) height = src.getHeight() - y;
if (width <= 0 || height <= 0) return null;
try {
CropImageFilter filter = new CropImageFilter(x, y, width, height);
FilteredImageSource fis = new FilteredImageSource(src.getSource(), filter);
Image croppedImg = Toolkit.getDefaultToolkit().createImage(fis);
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = result.createGraphics();
g2d.drawImage(croppedImg, 0, 0, null);
g2d.dispose();
return result;
} catch (Exception e) {
System.err.println("圖片裁剪失敗: " + e.getMessage());
return null;
}
}
/**
* 將 BufferedImage 儲存為檔案
*/
public static boolean saveImage(BufferedImage image, String path, String fileName, String format) {
if (image == null) return false;
try {
File dir = new File(path);
if (!dir.exists()) dir.mkdirs();
File file = new File(dir, fileName + "." + format.toLowerCase());
return ImageIO.write(image, format, file);
} catch (IOException e) {
System.err.println("儲存圖片失敗: " + e.getMessage());
return false;
}
}
// 測試主程式
public static void main(String[] args) {
// 1. 全螢幕截圖並儲存
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
boolean ok = captureScreenToFile(0, 0, screenSize.width, screenSize.height,
"./screenshots", "fullscreen", "png");
System.out.println("全螢幕截圖: " + (ok ? "成功" : "失敗"));
// 2. 區域截圖 (左上角 400x300)
BufferedImage region = captureScreen(100, 100, 400, 300);
if (region != null) {
saveImage(region, "./screenshots", "region_400x300", "png");
System.out.println("區域截圖完成");
// 3. 裁剪該區域的中心 200x150
BufferedImage cropped = cropImage(region, 100, 75, 200, 150);
if (cropped != null) {
saveImage(cropped, "./screenshots", "cropped_center", "png");
System.out.println("裁剪完成");
}
}
}
}
Robot.createScreenCapture 可跨螢幕截取,座標以主螢幕左上角為原點 (0,0)可進一步整合 OCR (Tesseract)、圖片比對 (OpenCV)、自動化測試 (SikuliX) 等技術,構建自動化操作與視覺驗證系統。