Android How to - Load Bitmap and scale








Question

We would like to know how to load Bitmap and scale.

Answer

//from  w  ww  . jav a 2  s. c o  m

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {
  public static Bitmap loadBitmapAnScale(final String filePath,
      final int width, final int height) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    options.inDither = false;
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[32 * 1024];
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);
    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    final Bitmap b = BitmapFactory.decodeFile(filePath, options);
    if (b != null) {
      final Bitmap bOut = Bitmap.createScaledBitmap(b, width, height,
          true);
      if (!bOut.equals(b)) {
        b.recycle();
      }
      return bOut;
    }

    return null;
  }

  private static int calculateInSampleSize(
      final BitmapFactory.Options options, final int reqWidth,
      final int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {

      final int halfHeight = height / 2;
      final int halfWidth = width / 2;

      // Calculate the largest inSampleSize value that is a power of 2 and
      // keeps both
      // height and width larger than the requested height and width.
      while ((halfHeight / inSampleSize) > reqHeight
          && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
      }
    }

    return inSampleSize;
  }
}