OutofMemoryError: bitmap size exceeds VM budget (Android)

后端 未结 9 760
甜味超标
甜味超标 2020-11-27 18:48

Getting an Exception in the BitmapFactory. Not sure what is the issue. (Well I can guess the issue, but not sure why its happening)

ERROR/AndroidRuntime(7906): jav         


        
9条回答
  •  心在旅途
    2020-11-27 19:01

    inSampleSize is a good hint. But a fixed value often doesn't work fine, since large bitmaps from files usually are user files, which can vary from tiny thumbnails to 12MP images from the digicam.

    Here's a quick and dirty loading routine. I know there's room for improvement, like a nicer coded loop, using powers of 2 for faster decoding, and so on. But it's a working start...

    public static Bitmap loadResizedBitmap( String filename, int width, int height, boolean exact ) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile( filename, options );
        if ( options.outHeight > 0 && options.outWidth > 0 ) {
            options.inJustDecodeBounds = false;
            options.inSampleSize = 2;
            while (    options.outWidth  / options.inSampleSize > width
                    && options.outHeight / options.inSampleSize > height ) {
                options.inSampleSize++;
            }
            options.inSampleSize--;
    
            bitmap = BitmapFactory.decodeFile( filename, options );
            if ( bitmap != null && exact ) {
                bitmap = Bitmap.createScaledBitmap( bitmap, width, height, false );
            }
        }
        return bitmap;
    }
    

    Btw, in the newer APIs there are also lots of BitmapFactory.Option's for fitting the image to screen DPIs, but I'm not sure whether they really simplify anything. Using android.util.DisplayMetrics.density or simply a fixed size for less memory consumption seem to work better imho.

提交回复
热议问题