圖庫項目中圖片尺寸控制是核心需求。本文提供基於 Java AWT/ImageIO 的完整實現,涵蓋按比例縮放、固定尺寸縮放、高質量 JPEG 輸出、批量處理目錄下所有圖片,並解決 com.sun.image.codec 受限 API 編譯問題。
public class ImageResizer {
/** 按倍數縮小:resizeTimes > 1 表示縮小 */
public BufferedImage resizeImage(BufferedImage src, float resizeTimes) {
int w = src.getWidth();
int h = src.getHeight();
int toW = (int) (w / resizeTimes);
int toH = (int) (h / resizeTimes);
return scale(src, toW, toH);
}
/** 按比例縮放:0 < ratio <= 1 為縮小,>1 為放大 */
public BufferedImage zoomImage(BufferedImage src, float ratio) {
int w = src.getWidth();
int h = src.getHeight();
int toW = (int) (w * ratio);
int toH = (int) (h * ratio);
return scale(src, toW, toH);
}
private BufferedImage scale(BufferedImage src, int w, int h) {
BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
dest.getGraphics().drawImage(
src.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null);
return dest;
}
/** 高質量 JPEG 輸出,質量 1.0 */
public boolean writeHighQuality(BufferedImage img, String destPath) {
try (FileOutputStream fos = new FileOutputStream(destPath)) {
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam(img);
param.setQuality(1f, true);
encoder.encode(img, param);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
public static void main(String[] args) throws Exception {
String input = "F:/pic/Chrysanthemum1.jpg";
String outputDir = "F:/picNew/";
float ratio = 0.25f; // 縮小至 1/4
ImageResizer resizer = new ImageResizer();
BufferedImage src = ImageIO.read(new File(input));
BufferedImage thumb = resizer.zoomImage(src, ratio);
String outName = outputDir + System.currentTimeMillis() + ".jpg";
resizer.writeHighQuality(thumb, outName);
}
public class BatchResize {
public static void main(String[] args) throws IOException {
File srcDir = new File("F:/pic");
File destDir = new File("F:/picNew");
if (!destDir.exists()) destDir.mkdirs();
float ratio = 0.25f;
ImageResizer resizer = new ImageResizer();
File[] images = srcDir.listFiles((dir, name) ->
name.toLowerCase().matches(".*\\.(jpg|jpeg|png|gif|bmp)"));
for (File f : images) {
BufferedImage src = ImageIO.read(f);
if (src == null) continue; // 跳過損壞文件
BufferedImage thumb = resizer.zoomImage(src, ratio);
String outPath = new File(destDir, f.getName()).getAbsolutePath();
resizer.writeHighQuality(thumb, outPath);
System.out.println("Processed: " + f.getName());
}
}
}
使用 com.sun.image.codec.jpeg.* 會提示 Forbidden reference。解決方案:
com.sun.media:jpeg 依賴,或改用標準 ImageIO.write() 配合 ImageWriteParam 設置質量(推薦,避免依賴內部 API)。javax.imageio.ImageIO + ImageWriteParam 替代 com.sun.* 內部類。Thumbnailator 或 TwelveMonkeys ImageIO 庫,一行代碼實現縮放、裁剪、水印、格式轉換。Arrays.stream(files).parallel().forEach(...)。掌握 BufferedImage、Graphics2D、ImageIO 核心 API 是 Java 圖像處理的基礎。實際項目中建議封裝通用工具類,結合成熟開源庫提升開發效率與穩定性。