2012-02-29 85 views
0

這是我的代碼。附加圖像時出現錯誤,內存不足

case RESULT_MEMORY_SELECT:  //SELECTING IMAGE FROM SD CARD 
       Uri photoUri = data.getData(); 
       String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
       Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null); 
        if (cursor.moveToFirst()) 
        { 
         int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
         String filePath = cursor.getString(columnIndex); 
         cursor.close(); 
         Bitmap imageReturned = BitmapFactory.decodeFile(filePath); 
         showViewOfReceiptInLayout(imageReturned); 
        } 
        break; 


public void showViewOfReceiptInLayout(Bitmap imageBitmap) 
     { 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
      imageSelected = baos.toByteArray(); // imageSelected is byteArray and i am storing this byte array in Database 
      imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 72, 72, false); 
      image.setVisibility(View.VISIBLE); // For Visible 
      image.setImageBitmap(imageBitmap); 


02-29 10:30:44.496: E/AndroidRuntime(7682): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 
02-29 10:30:44.496: E/AndroidRuntime(7682):  at android.graphics.Bitmap.nativeCreate(Native Method) 
02-29 10:30:44.496: E/AndroidRuntime(7682):  at android.graphics.Bitmap.createBitmap(Bitmap.java:468) 
02-29 10:30:44.496: E/AndroidRuntime(7682):  at android.graphics.Bitmap.createBitmap(Bitmap.java:435) 

有誰能告訴如何解決這個錯誤?

回答

0

以下是您必須縮小圖像大小以避免內存不足的解決方案。

BitmapFactory.Options options=new BitmapFactory.Options(); 
     options.inSampleSize = 8; 
     options.inJustDecodeBounds = true; 

     Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options); 

     final int REQUIRED_SIZE=70; 
     int width_tmp=options.outWidth, height_tmp=options.outHeight; 
     int scale=1; 
     while(true){ 
      if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
       break; 
      width_tmp/=2; 
      height_tmp/=2; 
      scale*=2; 
     } 

     //Decode with inSampleSize 
     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize=scale; 
     Bitmap btm=BitmapFactory.decodeStream(is, null, o2); 
     img_t.setImageBitmap(btm); 
+0

不會失去質量嗎?我不想減少我將要存儲在數據庫 – 2012-02-29 06:07:58

+0

中的圖像的大小和質量,但是根據我的意見,您將沒有別的選擇。 – Maneesh 2012-02-29 06:15:18

0

首先,你需要找到OOM原因:

如果您的應用程序內存使用解碼圖像之前大了,所以你需要釋放一些內存,釋放對象的引用,如果你不使用前解碼圖像物體。

你可以使用:adb shell dumpsys meminfo your_package_name顯示內存使用率

如果應用程序的內存使用情況是之前的解碼圖像很小,OOM是解碼圖像出現,如果出現這種情況,建議:

1.如果你的形象是大,當解碼,提供一個BitmapFactory.Option,該選項有inSampleSize使用小內存解碼圖像

2.make周圍的解碼方法try塊,趕上OutOfMemroyError

相關問題