scale bitmap to fit to MAX_WIDTH x MAX_HEIGHT bounding box - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

scale bitmap to fit to MAX_WIDTH x MAX_HEIGHT bounding box

Demo Code

import android.graphics.Bitmap;
import android.graphics.Matrix;

public class Main {

  /**/*from w w w .  j  av  a2 s  .c  o m*/
   * max picture width
   */
  private static final int MAX_WIDTH = 400;
  /**
   * max picture height
   */
  private static final int MAX_HEIGHT = 300;

  /**
   * scale bitmap to fit to MAX_WIDTH x MAX_HEIGHT bounding box
   * 
   * @param source
   *          bitmap we want to scale
   * @return scaled bitmap
   */
  public static Bitmap scaleBitmap(Bitmap source) {
    float scale = Math.min(MAX_WIDTH / (float) source.getWidth(), MAX_HEIGHT / (float) source.getHeight());
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);
    Bitmap result = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
    return result;
  }

}

Related Tutorials