Decoding bitmaps in Android with the right size

You may want to use inJustDecodeBounds. Set it to TRUE and load the file as it is.

The image won't be loaded into memory. But the outheight and outwidth properties of BitmapFactory.Options will contain the actual size params of the image specified. Calculate how much u want to subsample it. i.e. 1/2 or 1/4 or 1/8 etc. and assign 2/4/8 etc. accordingly to the inSampleSize.

Now set inJustDecodeBounds to FALSE and call BitmapFactory.decodeFile() to load the image of the exact size as calculated above.


You are on the right track, however you are trying to do two things at once: read the file in and scale it to the appropriate size.

The first step is to read the file to a Bitmap slightly bigger than you require, using BitmapFactory.Options.inSampleSize to ensure that you do not consume excessive memory reading a large bitmap when all you want is a smaller thumbnail or screen resolution image.

The second step is to call Bitmap.createScaledBitmap() to create a new bitmap to the exact resolution you require.

Make sure you clean up after the temporary bitmap to reclaim its memory. (Either let the variable go out of scope and let the GC deal with it, or call .recycle() on it if you are loading lots of images and are running tight on memory.)


First you need to sample the image to nearest sampling value so that bitmap become memory efficient, which you have described perfectly. Once it's done you can scale it up to fit your screen.

// This function taking care of sampling
backImage =decodeSampledBitmapFromResource(getResources(),R.drawable.back, width, height);

// This will scale it to your screen width and height. you need to pass screen width and height.
backImage = Bitmap.createScaledBitmap(backImage, width, height, false);