解決imageView載入圖片時候造成記憶體溢出的問題

來源:互聯網
上載者:User

標籤:記憶體溢出   imageview   圖片   


圖片載入  出現記憶體溢出的問題很普遍  而且解決的方法五花八門 各有優劣

主要是因為  imageView  在底層建立圖片層的時候 會佔用很大的記憶體空間

盡量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource直接使用圖片路徑來設定一張大圖,因為這些函數在完成decode後,最終都是通過java層的createBitmap來完成的,需要消耗更多記憶體。改用先通過BitmapFactory.decodeStream方法,建立出一個bitmap,再調用上述方法將其設為ImageView的 source。decodeStream最大的秘密在於其直接調用JNI>>nativeDecodeAsset()來完成decode,無需再使用java層的createBitmap,從而節省了java層的空間。下面是使用InputStream載入圖片的

長話短說,直接上一個自己寫的方法,好與不好,僅供參考。

/**    * 大圖片處理機制    * 利用Bitmap 轉存 R圖片    */   public static Bitmap btp;   public static void getBitmapForImgResourse(Context mContext,int imgId,ImageView mImageView) throws IOException {      InputStream is = mContext.getResources().openRawResource(imgId);      BitmapFactory.Options options = new BitmapFactory.Options();      options.inJustDecodeBounds = false;      options.inPreferredConfig = Bitmap.Config.RGB_565;      options.inPurgeable = true;      options.inInputShareable = true;      options.inSampleSize = 1;      btp = BitmapFactory.decodeStream(is, null, options);      mImageView.setImageBitmap(btp);//    btp.recycle();      is.close();   }

 
調用方式
Utils.getBitmapForImgResourse(mContext, object.getImgId(), holder.mImg);
第一參數context 第二參數 R.drawable.XX 第三參數  設定圖片的imageView
大家用一下看看好不好用  最好的onStop裡 將btp recycle()一下 


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

解決imageView載入圖片時候造成記憶體溢出的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.