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

Android 圖片處理實戰:透過 URI 取得 Bitmap 並完成壓縮與角度修正

編輯:關於 Android 開發

Android 圖片處理實戰:透過 URI 取得 Bitmap 並完成壓縮與角度修正

在調用系統圖庫選擇圖片時,很多人在 onActivityResult 中會直接用 MediaStore 來取得回傳的圖片:

Uri mImageCaptureUri = data.getData();
Bitmap photoBmp = null;
if (mImageCaptureUri != null) {
    photoBmp = MediaStore.Images.Media.getBitmap(ac.getContentResolver(), mImageCaptureUri);
}

然而,這種做法其實並不可取。我們來看看 Media.getBitmap() 的源碼:

public static final Bitmap getBitmap(ContentResolver cr, Uri url) throws FileNotFoundException, IOException {
    InputStream input = cr.openInputStream(url);
    Bitmap bitmap = BitmapFactory.decodeStream(input);
    input.close();
    return bitmap;
}

可以看到它非常簡單粗暴,回傳的是原始大小的 bitmap。當使用者從圖庫選的照片很大時,程式極有可能因此拋出 OOM(記憶體不足)。

一、在解碼前先壓縮,避免 OOM

為了避免 OOM,我們需要在 BitmapFactory.decodeStream 之前先進行壓縮。以下是改進後的做法,在 onActivityResult 中改為呼叫自訂方法:

Uri mImageCaptureUri = data.getData();
Bitmap photoBmp = null;
if (mImageCaptureUri != null) {
    photoBmp = getBitmapFormUri(ac, mImageCaptureUri);
}
/**
 * 通過 uri 獲取圖片並進行壓縮
 */
public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
    InputStream input = ac.getContentResolver().openInputStream(uri);
    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true;// optional
    onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    int originalWidth = onlyBoundsOptions.outWidth;
    int originalHeight = onlyBoundsOptions.outHeight;
    if ((originalWidth == -1) || (originalHeight == -1)) return null;

    // 圖片分辨率以 480x800 為標準
    float hh = 800f;// 高度設為 800f
    float ww = 480f;// 寬度設為 480f
    // 縮放比。由於是固定比例縮放,只用高或寬其中一個數據計算即可
    int be = 1;// be=1 表示不縮放
    if (originalWidth > originalHeight && originalWidth > ww) {
        be = (int) (originalWidth / ww);
    } else if (originalWidth < originalHeight && originalHeight > hh) {
        be = (int) (originalHeight / hh);
    }
    if (be <= 0) be = 1;
    // 比例壓縮
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = be;// 設置縮放比例
    bitmapOptions.inDither = true;// optional
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
    input = ac.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    input.close();
    return compressImage(bitmap);// 再進行質量壓縮
}

這裡的關鍵技巧是先用 inJustDecodeBounds = true 只讀取圖片尺寸而不真正載入像素,據此計算出合適的 inSampleSize,就能大幅降低記憶體佔用。

接著再進行一層質量壓縮:

/**
 * 質量壓縮方法
 */
public static Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量100表示不壓縮
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100) { // 若壓縮後仍大於 100kb 則繼續壓縮
        baos.reset();// 重置 baos 即清空
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 壓縮 options%
        options -= 10;// 每次都減少 10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    return BitmapFactory.decodeStream(isBm, null, null);
}

二、修正三星手機拍照後圖片旋轉 90 度的問題

OOM 解決了,卻又碰到另一個經典難題:用三星手機拍照或選照片後,回傳的圖片竟然旋轉了 90 度。這是由於部分裝置會透過 EXIF 資訊記錄拍攝方向,因此需要讀取旋轉角度並加以校正。在 onActivityResult 中進一步改進:

Uri originalUri = null;
File file = null;
if (null != data && data.getData() != null) {
    originalUri = data.getData();
    file = getFileFromMediaUri(ac, originalUri);
}
Bitmap photoBmp = getBitmapFormUri(ac, Uri.fromFile(file));
int degree = getBitmapDegree(file.getAbsolutePath());
// 把圖片旋轉為正的方向
Bitmap newbitmap = rotateBitmapByDegree(photoBmp, degree);

先透過 Uri 取得實際檔案:

/**
 * 通過 Uri 獲取文件
 */
public static File getFileFromMediaUri(Context ac, Uri uri) {
    if (uri.getScheme().toString().compareTo("content") == 0) {
        ContentResolver cr = ac.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            String filePath = cursor.getString(cursor.getColumnIndex("_data"));
            cursor.close();
            if (filePath != null) {
                return new File(filePath);
            }
        }
    } else if (uri.getScheme().toString().compareTo("file") == 0) {
        return new File(uri.toString().replace("file://", ""));
    }
    return null;
}

再讀取圖片的旋轉角度:

/**
 * 讀取圖片的旋轉的角度
 */
public static int getBitmapDegree(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;
}

最後依角度旋轉圖片:

/**
 * 將圖片按照某個角度進行旋轉
 */
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
    Bitmap returnBm = null;
    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    try {
        returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
    } catch (OutOfMemoryError e) {
    }
    if (returnBm == null) {
        returnBm = bm;
    }
    if (bm != returnBm) {
        bm.recycle();
    }
    return returnBm;
}

如此一來,OOM 與圖片旋轉的問題就全部搞定了!這套「比例壓縮 + 質量壓縮 + EXIF 角度校正」的組合,是處理圖庫選圖時相當實用的完整方案。

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