Android 載入大圖片造成OOM異常解決方案

來源:互聯網
上載者:User

Dalvik對android應用程式的最大記憶體有限制,而解析圖片又是比較耗資源的,比如說解析一個2048*1536的位元影像需要12M的記憶體,這通常會造成OOM。


解決方案:根據裝置的解析度降低待載入的圖片的品質,比如說裝置解析度為480*320,那麼只需要將待載入的圖片(比如:2048*1536)壓縮成480*320就可以了,至於怎麼壓縮android SDK提供瞭解決方案,具體作法如下:

/** * 根據圖片實際尺寸和待顯示尺寸計算圖片壓縮比率 * @param options * @param reqWidth顯示寬度 * @param reqHeight顯示高度 * @return壓縮比率 */public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {//實際寬、高final int height = options.outHeight;final int width = options.outWidth;int inSampleSize = 1;if (height > reqHeight || width > reqWidth) {final int heightRatio = Math.round((float) height/ (float) reqHeight);final int widthRatio = Math.round((float) width / (float) reqWidth);inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}/** * 根據顯示尺寸,擷取壓縮後的圖片 * @param res * @param resId * @param reqWidth顯示寬度 * @param reqHeight顯示高度 * @return */public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId, int reqWidth, int reqHeight) {final BitmapFactory.Options options = new BitmapFactory.Options();//不壓縮,擷取實際寬、高options.inJustDecodeBounds = true;BitmapFactory.decodeResource(res, resId, options);// 計算壓縮比率options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);// 設定壓縮選項options.inJustDecodeBounds = false;return BitmapFactory.decodeResource(res, resId, options);}

聯繫我們

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