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

Android 相機照片過大?用 Bitmap 三步行壓縮與旋轉校正

編輯:關於 Android 程式設計

手機鏡頭的解析度一路水漲船高,隨便一張照片就有好幾 MB。當 App 需要把拍下的照片上傳到伺服器時,這龐大的體積會直接反映在等待時間與行動網路流量上。的解法有兩條路:一是拍攝時就要求系統給縮圖,二是拍下原圖後自行壓縮。前者實作最省事,但畫質往往慘不忍睹;後者能在可接受範圍內兼顧清晰度與檔案大小,是正式專案裡更常採用的做法。

完整流程可以拆成三個步驟:降採樣解碼(避免大圖直接載入造成 OutOfMemoryError)、依 EXIF 校正方向(避免照片躺著)、重新編碼並調整品質。以下逐步說明。

步驟一:只讀邊長,先算出縮放倍率

關鍵在於 inJustDecodeBounds。設為 true 時,BitmapFactory 只解析檔案標頭取得寬高,不會真正配置像素記憶體。拿到原始尺寸後,再透過 inSampleSize 指定降採樣倍數,第二次解碼時記憶體用量就降到 1/n²。

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);

// 依目標尺寸計算 inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);

// 正式解碼
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(filePath, options);

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;
}

步驟二:讀 EXIF 把方向擺正

手機為了省下運算,多半是寫入方向資訊而非真的旋轉像素。若不處理,同一張照片在不同 App 裡會呈現不同角度。用 ExifInterface 取出方向標籤,再用 Matrix 補做旋轉即可。

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);
}

步驟三:重新編碼,決定檔案大小

compress() 的第二個參數就是 JPEG 品質值,範圍 0~100。傳 100 代表幾乎不做有損壓縮,傳 30 大約砍掉七成體積。實務上 50~80 之間通常是清晰度與大小的甜蜜點,涉及文字或票券的圖片則建議拉高到 80 以上。

bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
// 30 代表壓縮掉約 70%;100 則表示不壓縮

組裝成一個可直接呼叫的方法

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;
    }

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

    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;
}

實務提醒

這段程式回傳的是 Bitmap 物件,若目的是上傳,通常還需要再把它寫回檔案或轉成 byte[],並記得在不再使用時呼叫 recycle(),否則在圖片串流處理的場景裡很容易累積記憶體壓力。另外 ByteArrayOutputStream 會把整張圖暫存在記憶體中,若圖片偏大,改用 FileOutputStream 直接寫檔會更省。

若專案的 minSdk 已達較新版本,也可考慮改用 BitmapRegionDecoder 或 Android 內建的 ImageDecoder/BitmapFactory 搭配 Bitmap.Config.RGB_565 等策略進一步降低記憶體佔用;概念與本文一致,都是「先量尺寸、再降採樣、最後編碼」。

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