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

Android 簡易實戰教程(二十八):正確加載大圖片避免內存溢出

編輯:關於 Android 程式設計

Android 系統以 ARGB 格式表示每個像素,因此每個像素佔用 4 個位元組,很容易造成內存溢出(OOM)。假設手機內存較小,卻要加載一張像素極高的圖片,就會因內存不足而崩潰,而這種異常往往是無法被捕捉的。

需要特別注意的是,內存是否不足並非取決於圖片的檔案大小,最主要的關鍵其實是像素總數。因此,加載大圖片的重點在於設定合適的縮放比例。

基本原理如下:

* 計算機把圖片的所有像素資訊全部解析出來,保存至內存
* Android 以 ARGB 保存圖片的像素資訊
* 手機屏幕 320*480,總像素:153600
* 圖片寬高 2400*3200,總像素:7680000
* 演算法:計算縮放比率
  2400 / 320 = 7
  3200 / 480 = 6

完整程式碼如下:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View v) {
        // 解析圖片所需的參數都封裝在 Options 對象中
        Options opt = new Options();
        // 不為像素申請內存,只獲取圖片寬高
        opt.inJustDecodeBounds = true;
        BitmapFactory.decodeFile("sdcard/dog.jpg", opt);

        // 拿到圖片寬高
        int imageWidth = opt.outWidth;
        int imageHeight = opt.outHeight;

        Display dp = getWindowManager().getDefaultDisplay();
        // 拿到屏幕寬高
        int screenWidth = dp.getWidth();
        int screenHeight = dp.getHeight();

        // 計算縮放比例
        int scale = 1;   // 默認不縮放
        int scaleWidth = imageWidth / screenWidth;
        int scaleHeight = imageHeight / screenHeight;

        // 哪個縮放比例大就取哪個;>= 是為了防止比例相同時漏執行
        if (scaleWidth >= scaleHeight && scaleWidth >= 1) {
            // 只縮放比屏幕像素大的圖片
            scale = scaleWidth;
        } else if (scaleWidth < scaleHeight && scaleHeight >= 1) {
            scale = scaleHeight;
        }

        // 設置縮放比例
        opt.inSampleSize = scale;

        // 此時有了縮放比,再次為圖片申請內存並解析位圖
        opt.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opt);

        ImageView iv = (ImageView) findViewById(R.id.iv);
        iv.setImageBitmap(bm);
    }
}

關鍵技巧在於兩段式解碼:第一次將 inJustDecodeBounds 設為 true,此時 BitmapFactory 只讀取圖片的寬高資訊而不真正分配像素內存;接著計算出合適的 inSampleSize 縮放比例,再將 inJustDecodeBounds 設回 false 進行第二次解碼。如此一來,載入到記憶體中的便是縮放後的 Bitmap,既能顯示大圖,又能有效避免內存溢出。

執行結果如下:

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