Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Bitmap 圖片壓縮實作:取樣縮放、角度校正與品質壓縮

編輯:Android 開發實例

手機相機的解析度越來越高,一張照片動輒好幾 MB。若要把拍好的照片上傳到伺服器,在網速不佳的環境下不但緩慢,還會消耗大量行動數據。解決方式有兩條路:一是直接請相機拍小圖,二是把大圖壓縮。前者簡單但清晰度差,後者能在維持可接受畫質的前提下大幅縮小檔案,是實務上更常用的做法。

本文示範後者,完整流程包含三個步驟:取樣縮放、依 EXIF 校正角度、品質壓縮。

一、取樣縮放:避免記憶體溢出

直接把一張幾千萬畫素的圖片載入記憶體,幾乎一定會 OOM。正確做法是先只讀取圖片的尺寸資訊(不載入像素),算出合適的取樣率,再進行真正的解碼。

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;              // 只讀邊界,不載入像素
BitmapFactory.decodeFile(filePath, options);

// 計算 inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);

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

inJustDecodeBounds = true 是關鍵技巧:此時 decodeFile 會把 outWidth、outHeight 填進 options 卻不實際配置記憶體,讓我們能先知道尺寸再決定縮放比例。

二、依 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);
}

createBitmap 最後一個參數传 true 代表啟用雙線性濾波,旋轉後的邊緣會比較平滑。

三、品質壓縮

bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
// 30 代表品質 30%,約等於壓縮 70%;100 則是不壓縮

四、完整方法

public static Bitmap getSmallBitmap(String filePath) {

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

    // 計算 inSampleSize
    options.inSampleSize = calculateInSampleSize(options, 480, 800);

    // 以 inSampleSize 解碼
    options.inJustDecodeBounds = false;
    Bitmap bm = BitmapFactory.decodeFile(filePath, options);
    if (bm == null) {
        return null;
    }

    // 依 EXIF 校正角度
    int degree = readPictureDegree(filePath);
    bm = rotateBitmap(bm, degree);

    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
    } finally {
        if (baos != null) {
            try {
                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
        inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
    }

    return inSampleSize;
}

inSampleSize 只能是整數,且實際解碼時會被取 2 的次方(1、2、4、8……)。範例中取較大的比例,可保證縮放後的寬高都不會小於目標值。

實務補充

· 範例中的 compress() 只是把結果寫進 ByteArrayOutputStream,並沒有真的存檔。若要寫回檔案,需再將 baos 的內容輸出到 FileOutputStream。
· 此方法回傳的 Bitmap 使用完畢後記得呼叫 recycle(),否則在記憶體受限的舊版裝置上容易 OOM。
· 若需要「檔案大小盡量小」,比 compress 更有效率的做法是縮小尺寸本身;若需要「尺寸固定但檔案更小」,則降低品質參數。
· Android 4.4 以後可使用 BitmapFactory.Options.inPreferredConfig 搭配 ARGB_8888/RGB_565 控制每像素位元數,RGB_565 可再省一半記憶體(但沒有 alpha 通道)。
· 讀取外部檔案需在 Manifest 宣告 READ_EXTERNAL_STORAGE 或新版的分項媒體權限。
· 若只是要縮圖上傳,可直接使用 ExifInterface 搭配 sampling,或改用成熟函式庫(如 Glide 的 submit(width, height))處理,能省下不少邊角問題。

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