Android How to - Create Resized Bitmap








Question

We would like to know how to create Resized Bitmap.

Answer

The following methods show how to resize a Bitmap. The Bitmap is passed in as an array of bytes. We also set the new height and width in the parameters. The returned Bitmap is resized according to the new width and height.

/*  w w w  . j  a v a  2 s .co m*/
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {

  public static Bitmap createResizedBitmap(byte[] img, int newHeight,
      int newWidth) {

    // Calculate the correct sample size for the new resolution
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = calculateSampleSize(getBitmapDimesions(img),
        newHeight, newWidth);

    // Create a bitmap from the byte array, and scale it to 80px x 80px
    return Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(img, 0, img.length, options), 80,
        80, false);
  }

  private static int calculateSampleSize(BitmapFactory.Options options,
      int newHeight, int newWidth) {
    int sampleSize = 1;

    while (((options.outHeight / 2) / sampleSize) > newHeight
        && ((options.outWidth / 2) / sampleSize) > newWidth) {

      // Make sure the sample size is a power of 2.
      sampleSize *= 2;
    }
    return sampleSize;
  }

  private static BitmapFactory.Options getBitmapDimesions(byte[] img) {

    // Make sure the bitmap is not stored in memory!
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeByteArray(img, 0, img.length, options);

    return options;
  }
}