Resize image during decode from file to Bitmap in android

java.lang.OutOfMemoryError is the nightmare for any android developer. During image operation we may get this out of memory exception any time because our app uses all the memory allocated by android system to that app so it will give you out of memory error.

We encounter this error when we try to decode larger image using its path of sdcard to Bitmap. So we can skip this error by decoding image to smaller size.

We can avoid this problem or better to say restrict it to a level by creating Bitmap of required size and not the actual size.

Images taken from camera now a days are of more than 3000 and 4000 in resolution. So if we want to display them in GridView or ListView, we have to sample them down so it won’t create OOM or does not hang the UI.

For that we will use sample size to BitmapFactory.Options while decoding the image. It will load your image in smaller size compare to the original image and save your memory.

Google suggest that sample size should be in power of 2 so the below code contains the logic of creating sample size according to the maximum size you provide and then it will load your image with the resolution near to that maximum size.

Here is the direct function I create that you can use in your project by providing the file path of your image. You can find out how get the file path of any image from this article: Pick image from gallery before and after Kitkat version in Android

private Bitmap decodeFile(String imgPath)
  Bitmap b = null;
  int max_size = 1000;
  File f = new File(imgPath);
  try {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    FileInputStream fis = new FileInputStream(f);
    BitmapFactory.decodeStream(fis, null, o);
    int scale = 1;
    if (o.outHeight > max_size || o.outWidth > max_size)
      scale = (int) Math.pow(2, (int) Math.ceil(Math.log(max_size / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    fis = new FileInputStream(f);
    b = BitmapFactory.decodeStream(fis, null, o2);
  catch (Exception e)
  return b;

Share your views in comments!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s