Android載入圖片記憶體溢出問題解決方案

來源:互聯網
上載者:User

Android載入圖片記憶體溢出問題解決方案

   這篇文章主要介紹了Android載入圖片記憶體溢出問題解決方案,本文講解使用BitmapFactory.Options解決記憶體溢出問題,需要的朋友可以參考下

  1. 在Android軟體開發過程中,圖片處理是經常遇到的。 在將圖片轉換成Bitmap的時候,由於圖片的大小不一樣,當遇到很大的圖片的時候會出現超出記憶體的問題,為瞭解決這個問題Android API提供了BitmapFactory.Options這個類.

  2. 由於Android對圖片使用記憶體有限制,若是載入幾兆的大圖片便記憶體溢出。Bitmap會將圖片的所有像素(即長x寬)載入到記憶體中,如果圖片解析度過大,會直接導致記憶體OOM,只有在BitmapFactory載入圖片時使用BitmapFactory.Options對相關參數進行配置來減少載入的像素。

  3. BitmapFactory.Options相關參數詳解:

  (1).Options.inPreferredConfig值來降低記憶體消耗。

  比如:預設值ARGB_8888改為RGB_565,節約一半記憶體。

  (2).設定Options.inSampleSize 縮放比例,對大圖片進行壓縮 。

  (3).設定Options.inPurgeable和inInputShareable:讓系統能及時回 收記憶體。

  A:inPurgeable:設定為True時,表示系統記憶體不足時可以被回 收,設定為False時,表示不能被回收。

  B:inInputShareable:設定是否深拷貝,與inPurgeable結合使用,inPurgeable為false時,該參數無意義。

  (4).使用decodeStream代替其他方法。

  decodeResource,setImageResource,setImageBitmap等方法

  4.代碼部分:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public static Bitmap getBitmapFromFile(File file, int width, int height) {

 

BitmapFactory.Options opts = null;

if (null != file && file.exists()) {

 

if (width > 0 && height > 0) {

opts = new BitmapFactory.Options();

// 只是返回的是圖片的寬和高,並不是返回一個Bitmap對象

opts.inJustDecodeBounds = true;

// 資訊沒有儲存在bitmap裡面,而是儲存在options裡面

BitmapFactory.decodeFile(file.getPath(), opts);

// 計算圖片縮放比例

final int minSideLength = Math.min(width, height);

// 縮圖大小為原始圖片大小的幾分之一。根據業務需求來做。

opts.inSampleSize = computeSampleSize(opts, minSideLength,

width * height);

// 重新讀入圖片,注意此時已經把options.inJustDecodeBounds設回false

opts.inJustDecodeBounds = false;

// 設定是否深拷貝,與inPurgeable結合使用

opts.inInputShareable = true;

// 設定為True時,表示系統記憶體不足時可以被回 收,設定為False時,表示不能被回收。

opts.inPurgeable = true;

}

try {

return BitmapFactory.decodeFile(file.getPath(), opts);

} catch (OutOfMemoryError e) {

e.printStackTrace();

}

}

return null;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.