編輯:關於 Android 開發
在調用系統圖庫選擇圖片時,很多人在 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,我們需要在 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);
}
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 角度校正」的組合,是處理圖庫選圖時相當實用的完整方案。
全面理解 Android 屬性動畫:原理、API 與實戰
Android 屬性動畫完全指南 屬性動畫系統是一個相當強健的框架,它幾乎能把任何物件變成動畫。你可以依據時間的推移去改變任意物件的屬性來定義動畫,而完全不必理會這個物件
Android 進階系列(四):Activity 生命週期與 Intent 的顯式、隱式用法
Android 的三大基礎元件——Activity、Service 與 BroadcastReceiver——都必須靠 Intent 才能啟動。前面幾篇我們已經反覆用到
Linux 超時重傳時間(RTO)實作探究:為什麼重傳間隔是 1 秒
Linux 超時重傳時間(RTO)實作探究:為什麼重傳間隔是 1 秒 最近遇到網路超時問題要排查,大致依下面的思路走: 1、先排除代碼邏輯問題、TCP 相關 BUG、內
Android 音樂播放器完整源碼:歌詞同步、均衡器、收藏與 QQ5.0 風格側滑菜單
Android 音樂播放器完整源碼分享 這份開源的音樂播放器把常見功能都實作了一遍,包含歌詞顯示、均衡器、收藏清單、QQ 5.0 風格的側滑菜單,以及通知列播放控制。適合