萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java 圖片縮略圖生成實戰:單張與批量處理完整代碼

圖庫項目中圖片尺寸控制是核心需求。本文提供基於 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());
        }
    }
}

受限 API 編譯問題解決

使用 com.sun.image.codec.jpeg.* 會提示 Forbidden reference。解決方案:

  1. Eclipse:Window → Preferences → Java → Compiler → Errors/Warnings → Deprecated and restricted API → Forbidden references 設為 Warning。
  2. Maven/Gradle:添加 com.sun.media:jpeg 依賴,或改用標準 ImageIO.write() 配合 ImageWriteParam 設置質量(推薦,避免依賴內部 API)。

現代化改進方向

  • 使用 javax.imageio.ImageIO + ImageWriteParam 替代 com.sun.* 內部類。
  • 引入 Thumbnailator 或 TwelveMonkeys ImageIO 庫,一行代碼實現縮放、裁剪、水印、格式轉換。
  • 並行流處理大批量圖片:Arrays.stream(files).parallel().forEach(...)。
  • 支持 WebP、AVIF 等現代格式,需額外插件。

總結

掌握 BufferedImage、Graphics2D、ImageIO 核心 API 是 Java 圖像處理的基礎。實際項目中建議封裝通用工具類,結合成熟開源庫提升開發效率與穩定性。

copyright © 萬盛學電腦網 all rights reserved