附加图像时出错,内存不足

时间:2012-02-29 05:30:26

标签: java android eclipse

这是我的代码。

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)

任何人都可以告诉我如何修复此错误吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

首先,你需要找到原因:

如果在解码图像之前你的应用程序内存使用量很大,那么在解码图像之前需要释放一些内存,如果你不使用该对象就释放对象引用。

您可以使用:adb shell dumpsys meminfo your_package_name来显示内存使用情况

如果在解码图像之前应用程序内存使用量很小,那么oom就会出现解码图像,如果发生这种情况,建议:

1.如果您的图像较大,则在解码时提供BitmapFactory.Option,该选项有inSampleSize以使用小内存来解码图像

2.围绕解码方法设置try块,捕获OutOfMemroyError