Java 標準 API 中的 Robot 類別提供了強大的螢幕截圖功能,同時也能模擬滑鼠鍵盤操作。本文將詳細介紹如何使用 Robot 類別進行螢幕截圖,並搭配 CropImageFilter 與 FilteredImageSource 實現圖片裁剪。
截圖的關鍵在於 createScreenCapture(Rectangle rect) 方法,它需要一個 Rectangle 物件來定義螢幕上的矩形區域。建構 Rectangle 非常直觀:
new Rectangle(int x, int y, int width, int height)
四個參數分別代表矩形左上角的 X 座標、Y 座標,以及矩形的寬度和高度。該方法回傳 BufferedImage 物件,方便後續處理。
/**
* 指定螢幕區域截圖,回傳截圖的 BufferedImage 物件
* @param x 起始 X 座標
* @param y 起始 Y 座標
* @param width 截圖寬度
* @param height 截圖高度
* @return BufferedImage 截圖物件
*/
public BufferedImage getScreenShot(int x, int y, int width, int height) {
BufferedImage bfImage = null;
try {
Robot robot = new Robot();
bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));
} catch (AWTException e) {
e.printStackTrace();
}
return bfImage;
}
若需將截圖存檔,可使用 ImageIO.write() 方法:
/**
* 指定螢幕區域截圖並儲存到指定目錄
* @param x 起始 X 座標
* @param y 起始 Y 座標
* @param width 截圖寬度
* @param height 截圖高度
* @param savePath 檔案儲存路徑
* @param fileName 檔案名稱
* @param format 檔案格式(如 png, jpg)
*/
public void screenShotAsFile(int x, int y, int width, int height,
String savePath, String fileName, String format) {
try {
Robot robot = new Robot();
BufferedImage bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));
File path = new File(savePath);
File file = new File(path, fileName + "." + format);
ImageIO.write(bfImage, format, file);
} catch (AWTException | IOException e) {
e.printStackTrace();
}
}
截圖後若需裁剪,主要涉及 CropImageFilter 和 FilteredImageSource 兩個類別。以下為裁剪 BufferedImage 的完整範例:
/**
* BufferedImage 圖片裁剪
* @param srcBfImg 待裁剪的 BufferedImage
* @param x 裁剪起始點 X 座標
* @param y 裁剪起始點 Y 座標
* @param width 裁剪寬度
* @param height 裁剪高度
* @return 裁剪後的 BufferedImage
*/
public BufferedImage cutBufferedImage(BufferedImage srcBfImg, int x, int y, int width, int height) {
BufferedImage cutedImage = null;
CropImageFilter cropFilter = new CropImageFilter(x, y, width, height);
Image img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(srcBfImg.getSource(), cropFilter));
cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = cutedImage.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
return cutedImage;
}
裁剪後的圖片同樣可使用 ImageIO.write() 存檔,參考前述截圖存檔程式碼即可。
Robot 實例以提升效能