2012-11-27 67 views
0

我正在實現一個應用程序,其中一個活動以全屏顯示圖像視圖。現在我有一些圖像下載到應用程序的文件目錄中。我想在該活動中將圖像設置爲圖像視圖,爲此我縮小了較大的圖像。我在使用應用程序10到15分鐘後出現OutOfMemory錯誤。錯誤在BitmapFactory的decodeFile中。這裏是我的代碼:在Android中縮小圖像

public static int calculateInSampleSize(
     BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 
     if (width > height) { 
      inSampleSize = Math.round((float)height/(float)reqHeight); 
     } else { 
      inSampleSize = Math.round((float)width/(float)reqWidth); 
     } 
    } 
    return inSampleSize; 
} 

public static Bitmap decodeSampledBitmapFromFile(String imagePath, 
     int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(imagePath, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(imagePath, options); 

} 

現在我給reqHeight = 500和reqWidth = 500

這段代碼在Android指南頁中給出。有什麼我想念的,如果有的話,請幫助我。我嘗試了很多東西,但沒有得到任何解決方案。

回答

2

改變你的int inSampleSize = 1;以int inSampleSize = 2或3再次測試應用程序,我希望這將解決您的問題。我也建議insted這種技術,嘗試延遲加載所有你形象dowanload這樣做將不會有位圖和outOfMemoryError。喲可以有延遲加載 - https://github.com/thest1/LazyList

0

如果您要存儲由decodeSampledBitmapFromFile返回的位圖列表,可能會在您的應用程序中發生內存泄漏。嘗試檢查內存泄漏,並使用Bitmap.recycle()來回收位圖並幫助Android釋放內存。

1

嘗試使用此

Bitmap resizedbitmap2 = Bitmap.createScaledBitmap(your_bitmap, width, height, 
         true); 

它會幫助你。