首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 圖片格式轉換與線性縮放:JIMI 庫實戰指南

     編輯:Java 相關知識

核心問題:編碼與解碼

圖片格式轉換核心在於解決各種格式的編碼/解碼。推薦使用 JIMI 包,可從 https://java.sun.com/products/jimi/ 下載包、原始碼與 Demo。

格式支援現狀

  • JIMI 提供幾乎所有格式的解碼支援
  • 不提供 GIF 和 TIFF/TIFF 格式的編碼 API
  • GIF 編碼網上可找到相關原始碼
  • TIFF 編碼 JAI (https://java.sun.com/products/java-media/jai/) 提供,作者暫用 JPEG 編碼替代

JIMI 核心 API 位置

com.sun.jimi.core 中是 JIMI 核心處理 API。

轉 JPEG 完整程式碼

public void toJPG(String source, String dest, int quality) {
    if (dest == null || dest.trim().equals("")) dest = source;
    if (!dest.toLowerCase().trim().endsWith("jpg")) {
        dest += ".jpg";
        System.out.println("Overriding to JPG, output file: " + dest);
    }
    if (quality < 0 || quality > 100 || (quality + "").equals("")) {
        System.out.println("quality must between '0' and '100'");
        System.out.println("set to DEFAULT value:'75'");
        quality = 75;
    }
    try {
        JPGOptions options = new JPGOptions();
        options.setQuality(quality);
        ImageProducer image = Jimi.getImageProducer(source);  // 解碼:一行搞定
        JimiWriter writer = Jimi.createJimiWriter(dest);
        writer.setSource(image);
        writer.setOptions(options);  // 屬性設置,非必要
        writer.putImage(dest);       // 編碼輸出
    } catch (JimiException je) {
        System.err.println("Error: " + je);
    }
}

關鍵簡潔性:解碼與編碼極簡

  • 解碼: ImageProducer image = Jimi.getImageProducer(source); —— 完全透明,不關心原圖格式,只要在 JIMI 解碼範圍內
  • 編碼: 建立 Writer → 設定來源 → 設定選項(可選)→ putImage() 輸出

屬性設置:JPGOptions

JPGOptions options = new JPGOptions();
options.setQuality(quality);

com.sun.jimi.core.options.* 針對各編碼格式提供 getter/setter,方便設置屬性。

GIF 編碼替代方案:AnimatedGifEncoder

public void toGIF(String source, String dest) throws JimiException {
    // 1. 先轉 JPEG
    if (!dest.toLowerCase().trim().endsWith("jpg")) dest += ".jpg";
    toJPG(source, dest, 75);
    
    // 2. JPEG 轉 BufferedImage
    BufferedImage file_in = null;
    File file = new File(dest);
    try { file_in = javax.imageio.ImageIO.read(file); } 
    catch (IOException e) { e.printStackTrace(); }
    
    // 3. 清理暫存 JPEG,輸出 GIF
    int end = dest.lastIndexOf(".");
    file.deleteOnExit();
    file.renameTo(new File(dest.substring(0, end) + ".gif"));
    
    // 4. AnimatedGifEncoder 編碼
    AnimatedGifEncoder e = new AnimatedGifEncoder();
    e.start(dest);
    e.addFrame(file_in);
    e.finish();
}

注意事項

  • AnimatedGifEncoder 無法正確識別所有格式圖片,**必須先轉 JPEG**(最簡單用 ImageIO)
  • e.addFrame(file_in) 完成實際編碼
  • 最後 renameTo 消滅暫存 JPEG 證據
  • 此法非徹底,**最佳做法是修改 AnimatedGifEncoder 來源碼**
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved