提供靜態方法 Segmentation(),依傳入的目標寬高與座標,從來源圖片擷取指定矩形區域並回傳 Icon,適用於圖片縮圖、區域截取、驗證碼切割等場景。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class SegmentationImage {
public static Icon Segmentation(String imagePath, int x, int y, int width, int height) throws IOException {
// 1. 讀取原圖
BufferedImage src = ImageIO.read(new File(imagePath));
int srcW = src.getWidth(), srcH = src.getHeight();
// 2. 邊界檢查
if (x < 0 || y < 0 || x + width > srcW || y + height > srcH) {
throw new IllegalArgumentException("切割區域超出原圖範圍");
}
// 3. 擷取子圖(高效:直接共用資料陣列)
BufferedImage sub = src.getSubimage(x, y, width, height);
// 4. 包裝為 Icon 回傳
return new ImageIcon(sub);
}
}
BufferedImage 與原圖共用資料緩衝區,無額外記憶體複製,效能極佳。x, y 為左上角座標,width, height 為切割寬高(原程式碼參數命名易混淆,已重構)。IllegalArgumentException,呼叫端可捕獲處理。Icon icon = SegmentationImage.Segmentation("photo.jpg", 100, 50, 200, 150);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(null, label);
InputStream / byte[] 輸入,適配網路圖片。BufferedImage.TYPE_INT_ARGB 強制透明通道,避免 JPEG 無 Alpha 通道導致黑底。AffineTransformOp 實現切割同時縮放/旋轉。短小精悍的切割工具,掌握 getSubimage() 核心 API,即可靈活應對各類圖片區域操作需求。