668
技術社區[雲棲]
android加載大量圖片內存溢出bitmap size exceeds VM budget的解決辦法。
方法一:
在從網絡或本地加載圖片的時候,隻加載縮略圖。
/**
* 按照路徑加載圖片
* @param path 圖片資源的存放路徑
* @param scalSize 縮小的倍數
* @return
*/
public static Bitmap loadResBitmap(String path, int scalSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = scalSize;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
這個方法的確能夠少占用不少內存,可是它的致命的缺點就是,因為加載的是縮略圖,所以圖片失真比較嚴重,對於對圖片質量要求很高的應用,可以采用下麵的方法。
方法二:
運用JAVA的軟引用,進行圖片緩存,將經常需要加載的圖片,存放在緩存裏,避免反複加載。
關於軟引用(SoftReference)的詳細說明,請參看https://blog.csdn.net/helixiuqqq/article/details/6610199。下麵是我寫的一個圖片緩存的工具類。
/**
*
* @author larson.liu
* 該類用於圖片緩存,防止內存溢出
*/
public class BitmapCache {
static private BitmapCache cache;
/** 用於Chche內容的存儲*/
private Hashtable<Integer, BtimapRef> bitmapRefs;
/** 垃圾Reference的隊列(所引用的對象已經被回收,則將該引用存入隊列中)*/
private ReferenceQueue<Bitmap> q;
/**
* 繼承SoftReference,使得每一個實例都具有可識別的標識。
*/
private class BtimapRef extends SoftReference<Bitmap> {
private Integer _key = 0;
public BtimapRef(Bitmap bmp, ReferenceQueue<Bitmap> q, int key) {
super(bmp, q);
_key = key;
}
}
private BitmapCache() {
bitmapRefs = new Hashtable<Integer, BtimapRef>();
q = new ReferenceQueue<Bitmap>();
}
/**
* 取得緩存器實例
*/
public static BitmapCache getInstance() {
if (cache == null) {
cache = new BitmapCache();
}
return cache;
}
/**
* 以軟引用的方式對一個Bitmap對象的實例進行引用並保存該引用
*/
private void addCacheBitmap(Bitmap bmp, Integer key) {
cleanCache();// 清除垃圾引用
BtimapRef ref = new BtimapRef(bmp, q, key);
bitmapRefs.put(key, ref);
}
/**
* 依據所指定的drawable下的圖片資源ID號(可以根據自己的需要從網絡或本地path下獲取),重新獲取相應Bitmap對象的實例
*/
public Bitmap getBitmap(int resId, Context context) {
Bitmap bmp = null;
// 緩存中是否有該Bitmap實例的軟引用,如果有,從軟引用中取得。
if (bitmapRefs.containsKey(resId)) {
BtimapRef ref = (BtimapRef) bitmapRefs.get(resId);
bmp = (Bitmap) ref.get();
}
// 如果沒有軟引用,或者從軟引用中得到的實例是null,重新構建一個實例,
// 並保存對這個新建實例的軟引用
if (bmp == null) {
bmp = BitmapFactory.decodeResource(context.getResources(), resId);
this.addCacheBitmap(bmp, resId);
}
return bmp;
}
private void cleanCache() {
BtimapRef ref = null;
while ((ref = (BtimapRef) q.poll()) != null) {
bitmapRefs.remove(ref._key);
}
}
// 清除Cache內的全部內容
public void clearCache() {
cleanCache();
bitmapRefs.clear();
System.gc();
System.runFinalization();
}
}
在程序代碼中調用該類:
imageView.setImageBitmap(bmpCache.getBitmap(R.drawable.kind01, this));
這樣當你的imageView需要來回變換背景圖片時,就不需要再重複加載。
方法三:
及時銷毀不再使用的Bitmap對象。
if (bitmap != null && b!itmap.isRecycled()){
bitmap.recycle();
bitmap = null; // recycle()是個比較漫長的過程,設為null,然後在最後調用System.gc(),效果能好很多
}
System.gc();
方法四:
盡可能少的使用圖片資源。
這個有點像廢話哈。但我隻知道我們經理說服客戶改了一下需求,然後在一個動態的listView裏(最多時能有100多項),就一下子少加載了幾十張網絡圖片,這該能節約多少內存啊!
綜合運用以上四種方法,一般的項目,應該就能避免oom的錯誤。歡迎一起探討更好的關於“圖片內存溢出問題”的解決方案。
最後更新:2017-04-02 17:28:38