2011-02-10 59 views
1

我使用下面的代碼將圖像加載到ListActivity中的行。加載圖像拋出OutOfMemoryException

URL url = new URL(drink.getImageUri()); 
       InputStream fis = url.openStream(); 
       //Decode image size 
       BitmapFactory.Options o = new BitmapFactory.Options(); 
       o.inJustDecodeBounds = true; 
       BitmapFactory.decodeStream(fis, null, o); 
       int scale = 1; 
       if (o.outHeight > imageMaxSize || o.outWidth > imageMaxSize) { 
        scale = (int) Math.pow(2, (int) Math.round(Math.log((imageMaxSize/(double) Math.max(o.outHeight, o.outWidth))/Math.log(0.5)))); 
       } 
       fis.close(); 
       fis = url.openStream(); 
       //Decode with inSampleSize 
       BitmapFactory.Options o2 = new BitmapFactory.Options(); 
       o2.inSampleSize = scale; 
       bitmap = BitmapFactory.decodeStream(fis, null, o2); 

       fis.close(); 

imageMaxSize是screenHeight/7,所以每個圖像應該相當小。

我在上面的代碼中做了什麼錯誤嗎?我得到的所有錯誤都在第二行,我試圖實際加載位圖。

在此先感謝 羅蘭

+2

羅蘭,如果你增加`scale`的值試試2,4,8,16這個問題是否會消失? – 2011-02-10 20:37:44

+0

您是否嘗試過在第一張圖片上調用Bitmap.recycle()以確保它不存儲原始圖片和縮放圖片? – Cameron 2011-02-10 21:06:28

回答

-2

與上面的代碼包含以下代碼塊:

if (o.outHeight > imageMaxSize || o.outWidth > imageMaxSize) { 
        scale = (int) Math.pow(2, (int) Math.round(Math.log((imageMaxSize/(double) Math.max(o.outHeight, o.outWidth))/Math.log(0.5)))); 
       } 

它根本沒有完成它的工作。 WillyTates評論試圖增加比例使我檢查計算的結果,它總是返回1.

現在當我修好它,所以我得到4或8的規模,它的工作更好,我還沒有能夠回到錯誤。

感謝 羅蘭

0

我認爲這裏的關鍵是,你在列表的行這樣做。當您完成清理內存時,您需要回收Bitmap。這可能不會在您的代碼的第一次迭代中發生,但由於您沒有使用Bitmap.recycle()回收內存,因此最終會耗盡內存並獲得「位圖超出VM預算」

0

更好的回答公認的答案。

基本上有時會因爲四捨五入Math.round(等)將全面規模回到1

1意味着即使您的圖片太大縮放。

我做了一個簡單的校驗後,秤的規模檢查。

if (o.outHeight > imageMaxSize || o.outWidth > imageMaxSize) { 
     scale = (int) Math.pow(2, (int) Math.round(Math.log((imageMaxSize/(double) Math.max(o.outHeight, o.outWidth))/Math.log(0.5)))); 
     // We already checked it was larger than acceptable so we know we at 
     // least need to scale down one step 
     if (scale == 1) { 
      scale = 2; 
     } 

    } 
相關問題