核心壓縮類 CompressPicDemo
public class CompressPicDemo {
private File srcFile;
private String inputDir, outputDir, inputFileName, outputFileName;
private int targetWidth = 100, targetHeight = 100;
private boolean proportional = true; // 等比縮放
// Setter 略...
public String compress() {
try {
srcFile = new File(inputDir, inputFileName);
if (!srcFile.exists()) return "not_found";
Image img = ImageIO.read(srcFile);
if (img.getWidth(null) == -1) return "read_failed";
int w, h;
if (proportional) {
double scaleW = (double) img.getWidth(null) / targetWidth;
double scaleH = (double) img.getHeight(null) / targetHeight;
double scale = Math.max(scaleW, scaleH); // 取較大縮放比,確保長邊符合限制
w = (int) (img.getWidth(null) / scale);
h = (int) (img.getHeight(null) / scale);
} else {
w = targetWidth; h = targetHeight;
}
BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(
img.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null);
try (FileOutputStream out = new FileOutputStream(new File(outputDir, outputFileName))) {
// 使用標準 ImageIO JPEG Writer 替代舊式 com.sun.image.codec.jpeg
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.85f); // 0.0-1.0 品質/體積平衡
writer.setOutput(ImageIO.createImageOutputStream(out));
writer.write(null, new IIOImage(tag, null, null), param);
writer.dispose();
}
return "ok";
} catch (IOException e) {
throw new RuntimeException("壓縮失敗", e);
}
}
}
關鍵改進點(對比原始碼)
- 移除 `com.sun.image.codec.jpeg`:屬於 Sun 專有 API,Java 9+ 已移除,改用標準
ImageIO + ImageWriter。
- 等比縮放邏輯修正:使用 `Math.max(scaleW, scaleH)` 確保長邊不超過目標尺寸,原始碼 `+0.1` 屬 Hack 寫法。
- 品質參數化:`param.setCompressionQuality(0.85f)` 可外部配置。
- try-with-resources:自動關閉流,避免洩漏。
縮放算法選擇
| 算法常數 | 速度 | 品質 | 適用場景 |
| `Image.SCALE_FAST` | 最快 | 低(鋸齒明顯) | 縮圖預覽、即時預覽 |
| `Image.SCALE_SMOOTH` | 中等 | 高(雙線性插值) | **生產環境推薦** |
| `Image.SCALE_AREA_AVERAGING` | 較慢 | 極高(區域平均) | 大幅縮小、科學影像 |
| `AffineTransformOp` (BICUBIC) | 最慢 | 最高(雙三次插值) | 專業攝影、印刷級 |
現代化庫推薦
- Thumbnailator:`Thumbnails.of(src).size(w,h).outputQuality(0.85).toFile(dest)` 一行搞定。
- TwelveMonkeys ImageIO:補足 JDK 不支援格式(TIFF、PSD、WebP 等)。
- ImageMagick (CLI/JNI):極致效能、功能最全,適合高吞吐服務。