首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 實現螢幕截圖與圖片裁剪完整指南

     編輯:Java 程式設計入門

Java 標準 API 中的 Robot 類別提供了強大的螢幕截圖功能,同時也能模擬滑鼠鍵盤操作。本文將詳細介紹如何使用 Robot 類別進行螢幕截圖,並搭配 CropImageFilter 與 FilteredImageSource 實現圖片裁剪。

核心方法:createScreenCapture

截圖的關鍵在於 createScreenCapture(Rectangle rect) 方法,它需要一個 Rectangle 物件來定義螢幕上的矩形區域。建構 Rectangle 非常直觀:

new Rectangle(int x, int y, int width, int height)

四個參數分別代表矩形左上角的 X 座標、Y 座標,以及矩形的寬度和高度。該方法回傳 BufferedImage 物件,方便後續處理。

指定區域截圖並回傳 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() 存檔,參考前述截圖存檔程式碼即可。

實務應用提示

  • 多螢幕環境下,座標系統以主螢幕左上角為原點 (0,0)
  • 高解析度螢幕 (Retina/4K) 可能需考慮縮放比例
  • 大量截圖時建議複用 Robot 實例以提升效能
  • 裁剪座標以原始圖片左上角為基準,非螢幕座標
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved