Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片壓縮的三種實作方式詳解

編輯:關於 Android 程式設計

Android 早期每個應用的堆上限只有十幾 MB,一張手機拍攝的照片就可能輕鬆超過 2MB,直接載入幾乎必然觸發 OutOfMemoryError。因此在上傳、縮圖、清單預覽等場景中,壓縮是必經之路。實務上常見的做法有三種:品質壓縮、比例(尺寸)壓縮,以及兩者混合。以下逐一說明。

方法一:品質壓縮

利用 Bitmap.compress() 的 quality 參數,迴圈遞減直到檔案大小落到目標範圍內。這種方式不改變圖片尺寸,只降低 JPEG 編碼品質。

private Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // 100 表示不壓縮,先將資料寫入 baos
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    int options = 100;
    // 迴圈判斷:若壓縮後仍大於 100KB,繼續降品質
    while (baos.toByteArray().length / 1024 > 100) {
        baos.reset();          // 清空緩衝區
        options -= 10;         // 每次遞減 10
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
    return bitmap;
}

關鍵點是 baos.reset():每次重壓前必須清空,否則資料會不斷累加,體積只會越來越大。

方法二:按比例縮放(依檔案路徑載入)

這種方式先只讀取圖片的寬高、不真正載入像素,算出縮放倍數後再重新解碼。它能大幅降低記憶體峰值,是處理大圖的首選。

private Bitmap getimage(String srcPath) {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // 第一次只讀邊界資訊,不載入像素
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // 此時 bitmap 為 null

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;

    // 以 800*480 作為目標基準
    float hh = 800f;  // 高度上限
    float ww = 480f;  // 寬度上限

    int be = 1;       // be = 1 表示不縮放
    if (w > h && w > ww) {
        be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) {
        be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) {
        be = 1;
    }
    newOpts.inSampleSize = be;   // 設定縮放倍數

    // 第二次才真正解碼
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
    return compressImage(bitmap); // 尺寸縮完後再走一次品質壓縮
}

inSampleSize 只能是整數,且解碼時會以 2 的冪次做近似取捨,因此它適合「把圖縮小」而非「精準裁到某個尺寸」。

也有人採用同時考慮寬高的平均算法,據說速度較快:

be = (int) ((w / STANDARD_WIDTH + h / STANDARD_HEIGHT) / 2);

結論是:縮放倍數取「寬度倍數與高度倍數的平均值」。這只是其中一種權衡,實際效果仍建議以自己的圖源實測比較。

方法三:兩者結合(依 Bitmap 物件壓縮)

先做一次品質預處理避免後續解碼爆掉,再用 Options 做比例縮放,最後補一道品質壓縮。這是最貼近生產環境的組合拳。

private Bitmap comp(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    // 若大於 1M,先降質避免 decodeStream 時溢出
    if (baos.toByteArray().length / 1024 > 1024) {
        baos.reset();
        image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;

    float hh = 800f;
    float ww = 480f;

    int be = 1;
    if (w > h && w > ww) {
        be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) {
        be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0) {
        be = 1;
    }
    newOpts.inSampleSize = be;
    // 由 ARGB_8888 降為 RGB_565,記憶體佔用直接減半
    newOpts.inPreferredConfig = Config.RGB_565;

    isBm = new ByteArrayInputStream(baos.toByteArray());
    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    return compressImage(bitmap);
}

這裡有兩個容易被忽略的細節:

  • inPreferredConfig = Config.RGB_565 放棄了透明通道,每個像素從 4 位元組降到 2 位元組。若圖片需要保留透明效果(例如 PNG 圖示),則不能這樣處理。
  • 重新解碼前要重建 ByteArrayInputStream,因為串流讀過一次就到底了。

選用建議

只在意體積、尺寸不變:用方法一。要處理相簿裡動輒數 MB 的大圖:方法二。需要兼顧記憶體峰值與畫質:方法三。另外別忘了,用完的 Bitmap 若不再需要,及早丟開引用讓 GC 接手,比反覆壓縮更能救你的 App。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved