2013-03-28 25 views
0

我有一個間歇性的問題,從Camera活動捕捉圖像,將其保存到一個較小的大小,並上傳保存的圖像到我的服務器。安卓 - OutOfMemoryError下采樣大型相機圖像

如果圖像文件大於特定閾值(我用2,000KB)我打電話下面的函數下采樣,並保存較小的圖像大:

private void downsampleLargePhoto(Uri uri, int fileSizeKB) 
{ 
    int scaleFactor = (int) (fileSizeKB/fileSizeLimit); 
    log("image is " + scaleFactor + " times too large"); 

    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    try 
    {   
     options.inJustDecodeBounds = false; 
     options.inSampleSize = scaleFactor; 
     Bitmap scaledBitmap = BitmapFactory.decodeStream(
        getContentResolver().openInputStream(uri), null, options); 
     log("scaled bitmap has size " + scaledBitmap.getWidth() + " x " + scaledBitmap.getHeight()); 

     String scaledFilename = uri.getPath(); 
     log("save scaled image to file " + scaledFilename); 
     FileOutputStream out = new FileOutputStream(scaledFilename); 
     scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
     scaledBitmap.recycle(); 

     File image = new java.io.File(scaledFilename); 
     int newFileSize = (int) image.length()/1000; 
     log("scaled image file is size " + newFileSize + " KB"); 
    } 
    catch(FileNotFoundException f) 
    { 
     log("FileNotFoundException: " + f); 
    } 
} 

有了非常大的圖像,但是,我的應用程序崩潰與線上的OutOfMemoryError:

Bitmap scaledBitmap = BitmapFactory.decodeStream(
        getContentResolver().openInputStream(uri), null, options); 

我還能做些什麼來縮小圖像?

+0

這已經在這裏找到答案之前 [1]:http://stackoverflow.com/questions/477572/strange-out-of-memory-issue-while-loading-an-image-到一個位圖對象/ 823966#823966 – thernav

回答

0

你還沒有真正嘗試過正確使用API​​。你應該設置inJustDecodeBounds = true,然後調用decodeStream()。一旦你有解碼圖像的大小,然後你選擇一個合適的inSampleSize值 - 它應該是(a)2的冪,並且(b)與壓縮圖像文件大小無關 - 然後調用decodeStream( )第二次。

爲了選擇合適的inSampleSize值,我通常會指向屏幕大小,即如果圖像最大邊緣的尺寸是屏幕最大邊緣的兩倍,則設置inSampleSize = 2。等等,等等