使用 ImageIO 讀取上傳圖片,計算縮放比例配合 AffineTransformOp 生成高品質縮圖,支援 JPG/PNG/GIF 格式轉換,並提供 Linux 無圖形介面環境的 headless 參數設定。
public boolean createThumbnail(String fromDir, String toDir,
String imgFile, String sysImgPrefix) throws Exception {
File src = new File(fromDir, imgFile);
BufferedImage bi = ImageIO.read(src);
// 目標最大寬高 120px,等比縮放
double ratio = 1.0;
if (bi.getHeight() > 120 || bi.getWidth() > 120) {
ratio = bi.getHeight() > bi.getWidth() ?
120.0 / bi.getHeight() : 120.0 / bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(
AffineTransform.getScaleInstance(ratio, ratio), null);
BufferedImage thumb = op.filter(bi, null);
// 格式判斷:JPG 維持,GIF 轉 PNG (ImageIO 限制)
String ext = isJpg(imgFile) ? "jpg" : "png";
File dest = new File(toDir, sysImgPrefix + "." + ext);
ImageIO.write(thumb, ext, dest);
return true;
}
export DISPLAY=host:0.0。-Djava.awt.headless=true 即可。ImageIO.read/write:統一圖片 I/O,支援插件擴充格式。BufferedImage.getScaledInstance:簡易縮放 (品質較低)。AffineTransformOp + AffineTransform.getScaleInstance:高品質雙三次/雙線性插值縮放。