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

Android 圖片壓縮實作:inSampleSize 解碼、Exif 校正與 JPEG 品質

編輯:關於 Android 程式設計

手機相機的解析度愈來愈高,一張照片動輒數 MB。若要把拍好的照片上傳到伺服器,在行動網路上不僅慢,还很耗流量。的解法有兩條路:一是拍照時直接取縮圖,二是把大圖壓縮。前者實作容易但清晰度明顯不足;後者能在維持可接受畫質的前提下大幅縮小檔案,是比較實用的做法。

壓縮的關鍵觀念是:不要先把整張大圖載入記憶體再處理,否則很容易 OOM。正確順序是「只讀尺寸 → 計算縮放倍率 → 縮圖解碼 → 依 Exif 校正角度 → 重新編碼」。

步驟一:只讀尺寸,計算 inSampleSize

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;               // 只讀邊界,不配置像素記憶體
BitmapFactory.decodeFile(filePath, options);

options.inSampleSize = calculateInSampleSize(options, 480, 800);

options.inJustDecodeBounds = false;              // 這次真的解碼
Bitmap bm = BitmapFactory.decodeFile(filePath, options);

步驟二:依 Exif 資訊校正拍攝方向

手機拍照時,方向資訊存在 Exif 裡而非像素中,若不處理,直式拍的照片上傳後會變成橫躺。

int degree = readPictureDegree(filePath);
bm = rotateBitmap(bm, degree);

private static int readPictureDegree(String path) {
    int degree = 0;
    try {
        ExifInterface exifInterface = new ExifInterface(path);
        int orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:  degree = 90;  break;
            case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break;
            case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return degree;
}

private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
    if (bitmap == null) return null;
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    Matrix mtx = new Matrix();
    mtx.postRotate(rotate);
    return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}

步驟三:重新編碼並指定品質

bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
// 第二個參數是品質,100 為近乎不壓縮,30 代表壓掉約七成資料量

完整方法

public static Bitmap getSmallBitmap(String filePath) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    options.inSampleSize = calculateInSampleSize(options, 480, 800);
    options.inJustDecodeBounds = false;
    Bitmap bm = BitmapFactory.decodeFile(filePath, options);
    if (bm == null) return null;

    bm = rotateBitmap(bm, readPictureDegree(filePath));

    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
    } finally {
        try {
            if (baos != null) baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return bm;
}

縮放倍率的計算邏輯

private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio  = Math.round((float) width  / (float) reqWidth);
        // 取較大者,確保縮完後的兩邊尺寸都不小於需求
        inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
    }
    return inSampleSize;
}

inSampleSize 只接受整數,且解碼時會以 2 的次方倍數縮減,因此它決定的是「解析度」,而 compress 的品質參數決定的是「編碼後的位元率」。兩者搭配使用,才能在清晰度與檔案大小之間取得平衡。

實務建議

  • 縮完的 Bitmap 若不再使用,記得 recycle()(4.4 以前效果明顯)。
  • compress 寫入 ByteArrayOutputStream 會在記憶體中再存一份完整資料,檔案很大時建議直接寫進檔案串流。
  • 上傳前可先比對原檔與壓縮後的大小,避免對小圖做無意義的重編碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved