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

Android 圖片處理實戰:修正拍照旋轉與等比縮圖

編輯:關於 Android 程式設計

只要 App 裡有拍照功能,就一定會遇到這兩個問題:照片方向莫名其妙歪掉,以及照片檔案大得嚇人。這篇把兩個處理環節整理清楚。

一、修正拍照後的自動旋轉

部分機型(三星手機是典型)拍完照,照片會出現 90 度或 180 度的偏移。原因不在圖片本身,而在 EXIF 資訊裡記錄了一個方向值,相機為了省算力選擇「記錄方向」而不是「真的旋轉像素」。所以我們要讀出那個角度,再補做一次真正的旋轉。

Bitmap bitmap = BitmapFactory.decodeFile(Const.ACT_CREATE_PIC_PATH.concat(photoName));

int angle = imageUtils.getExifOrientation(Const.ACT_CREATE_PIC_PATH.concat(photoName));
if (angle != 0) {
    // 照片帶有旋轉資訊,依角度還原
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    bitmap = Bitmap.createBitmap(bitmap, 0, 0,
            bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

讀取 EXIF 方向的核心 API 是 ExifInterface:

public static int getExifOrientation(String path) throws IOException {
    ExifInterface exif = new ExifInterface(path);
    int orientation = exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:  return 90;
        case ExifInterface.ORIENTATION_ROTATE_180: return 180;
        case ExifInterface.ORIENTATION_ROTATE_270: return 270;
        default: return 0;
    }
}

二、縮圖:多數場景不需要 3MB 的原圖

主流手機拍出的照片動輒 3MB 以上。如果這張圖要加濾鏡、要上傳,耗時與流量都很可觀。但實際上,手機螢幕檢視圖片時根本用不到那麼高的解析度——高解析度只有在看大圖、印刷時才有意義。

因此在不需要裁剪的前提下,可以自己等比縮小解析度:

public String scaleDown(String path, Context context) {
    Bitmap orignalB = BitmapFactory.decodeFile(path);

    // 以長寬較大的一邊縮到 974 px 為目標,計算縮放比例
    float ratio = Math.min((float) 974 / orignalB.getWidth(),
                           (float) 974 / orignalB.getHeight());

    int width  = Math.round(ratio * orignalB.getWidth());
    int height = Math.round(ratio * orignalB.getHeight());

    Bitmap newB = Bitmap.createScaledBitmap(orignalB, width, height, true);

    String imgName = path.substring(path.lastIndexOf("/") + 1);
    String userId  = UserHelper.getUserId(context);
    String newpath = createDirectoryAndSaveFile(newB, userId + System.currentTimeMillis() + ".jpg");

    orignalB.recycle();
    newB.recycle();
    return newpath;
}

幾個細節值得注意:

  • 用 Math.min 而不是 max:我們要保證長寬都不超過目標值,所以取兩個比例中較小的那個,否則短邊會被放大。
  • 第四個參數 true:表示採用雙線性濾波縮放,畫質比 false 好,代價是多一點運算。
  • 記得 recycle:Bitmap 的像素記憶體不在 Java 堆上(Android 2.x)或需要明確釋放,用完立刻 recycle(),並把參照設為 null,否則 OOM 找上門。

三、如果連 decode 都會 OOM

直接 decodeFile 一张 4000×3000 的圖,本身就會配置約 48MB 記憶體,低階機必爆。正確做法是用 BitmapFactory.Options 做「兩段式解碼」:先只讀尺寸,再決定 inSampleSize。

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;                       // 第一階段:只讀邊界,不載入像素
BitmapFactory.decodeFile(path, opts);

int sample = 1;
while (opts.outWidth / (sample * 2) >= 974
        && opts.outHeight / (sample * 2) >= 974) {
    sample *= 2;                                      // inSampleSize 必須是 2 的冪次
}

opts.inSampleSize = sample;
opts.inJustDecodeBounds = false;                      // 第二階段:真正解碼
Bitmap bitmap = BitmapFactory.decodeFile(path, opts);

這樣一來,解碼時配置的就是縮小後的記憶體,從源頭避開 OOM,比事後縮圖安全得多。

四、完整流程建議

  1. 拍照存到 App 私有目錄(避免污染媒體庫,也不用等 MediaScanner)。
  2. 讀 EXIF 方向,用 Matrix 旋轉還原。
  3. 用 inSampleSize 兩段式解碼控制記憶體。
  4. 需要時再做精確的等比縮放與 JPEG 品質壓縮。
  5. recycle 中間產生的 Bitmap,只保留最終版本。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved