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

Java 螢幕截圖與圖片裁剪完整實作

     編輯:Java 相關知識

Java Robot 類別螢幕截圖與圖片處理

Java 標準 API 中的 java.awt.Robot 類別提供了強大的螢幕截圖、滑鼠鍵盤模擬等功能。結合 BufferedImage、ImageIO 以及影像過濾器,可以輕鬆實作螢幕截圖、儲存檔案與區域裁剪功能。本文提供完整可執行的工具類實作。

核心類別與方法

  • Robot.createScreenCapture(Rectangle):擷取指定矩形區域螢幕畫面
  • Rectangle(x, y, width, height):定義截圖區域左上角座標與寬高
  • ImageIO.write(RenderedImage, format, File):將圖片儲存為檔案
  • CropImageFilter + FilteredImageSource:實作圖片區域裁剪

完整工具類實作

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)
  • 高 DPI 螢幕:Retina/4K 螢幕下座標單位為邏輯像素,實際像素可能需乘以縮放比例
  • 權限問題:某些作業系統需授予螢幕錄製權限 (macOS 系統偏好設定 → 安全性與隱私 → 螢幕錄製)
  • 效能考量:頻繁截圖會消耗 CPU/記憶體,建議控制頻率或使用非同步處理
  • 影像格式選擇:PNG 無損壓縮適合截圖;JPEG 有損壓縮體積較小適合照片

擴充應用方向

可進一步整合 OCR (Tesseract)、圖片比對 (OpenCV)、自動化測試 (SikuliX) 等技術,構建自動化操作與視覺驗證系統。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved