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

優化 Android 相機與相簿取圖:避免 OOM

編輯:Android 開發實例

直接從相機或相簿取得圖片後,若只用 ImageView.setImageURI(uri) 顯示,短期看似正常,但反覆操作後容易因 Bitmap 無法回收而導致記憶體不足。問題核心在於圖片解析度過高,載入後佔用大量記憶體。

為什麼會崩潰

Android 載入圖片時,記憶體消耗主要取決於圖片的像素數量,而不是檔案大小。高解析度照片即使 JPEG 體積不大,解碼後仍可能非常龐大。若沒有妥善回收,GC 也未必能即時釋放足夠記憶體。

優化流程

  1. 取得圖片 Uri。
  2. 用 ContentResolver.openInputStream(uri) 取得輸入流。
  3. 先用 inJustDecodeBounds 讀取圖片尺寸,不載入完整像素。
  4. 比較圖片尺寸與螢幕尺寸,計算 inSampleSize。
  5. 再以縮放後的設定重新解碼。
  6. 使用完畢後,依需要呼叫 recycle() 釋放不再使用的 Bitmap。

關鍵程式碼

Uri uri = data.getData();
InputStream is = getContentResolver().openInputStream(uri);

WindowManager wm = getWindowManager();
int windowWidth = wm.getDefaultDisplay().getWidth();
int windowHeight = wm.getDefaultDisplay().getHeight();

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, opts);

int bitmapWidth = opts.outWidth;
int bitmapHeight = opts.outHeight;

if (bitmapHeight > windowHeight || bitmapWidth > windowWidth) {
    int scaleX = bitmapWidth / windowWidth;
    int scaleY = bitmapHeight / windowHeight;
    opts.inSampleSize = Math.max(scaleX, scaleY);
} else {
    opts.inSampleSize = 1;
}

opts.inJustDecodeBounds = false;
is = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);

回收與重用

Bitmap 提供 isRecycled() 與 recycle() 兩個方法。若某張 Bitmap 已不再使用,可先判斷是否已回收,再強制釋放,降低記憶體壓力。

if (bitmap != null && !bitmap.isRecycled()) {
    bitmap.recycle();
}

對於需要頻繁載入圖片的應用,建議建立快取與釋放策略,避免同時保留過多高解析度 Bitmap。若只是簡單展示,可先做解析度優化;若是商業級圖片應用,則應更明確地管理 Bitmap 生命週期。

延伸閱讀:

  • https://www.fengfly.com/plus/view-214101-1.html
  • https://www.fengfly.com/plus/view-214216-1.html
  • https://www.fengfly.com/plus/view-213512-1.html
  • https://www.fengfly.com/plus/view-214093-1.html

小結:取圖功能看似簡單,但真正重要的是記憶體管理。先縮放、再顯示、適時回收,才能讓應用穩定運行。

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