2012-02-29 83 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

相关问题