Saturday, 20 October 2012

Android - how to scale a bitmap and retain the original's quality

If you've tried the Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter) method you'll have experienced the bad (blocky) quality of the Bitmap that it produces. Here's an alternative method I found (didn't compose myself) for scaling Bitmaps and retaining the quality of the original:

/**
 * Scales the provided bitmap to have the height and width provided.
 * (Alternative method for scaling bitmaps
 * since Bitmap.createScaledBitmap(...) produces bad (blocky) quality bitmaps.)
 * 
 * @param bitmap is the bitmap to scale.
 * @param newWidth is the desired width of the scaled bitmap.
 * @param newHeight is the desired height of the scaled bitmap.
 * @return the scaled bitmap.
 */
 public static Bitmap scaleBitmap(Bitmap bitmap, int newWidth, int newHeight) {
  Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);

  float scaleX = newWidth / (float) bitmap.getWidth();
  float scaleY = newHeight / (float) bitmap.getHeight();
  float pivotX = 0;
  float pivotY = 0;

  Matrix scaleMatrix = new Matrix();
  scaleMatrix.setScale(scaleX, scaleY, pivotX, pivotY);

  Canvas canvas = new Canvas(scaledBitmap);
  canvas.setMatrix(scaleMatrix);
  canvas.drawBitmap(bitmap, 0, 0, new Paint(Paint.FILTER_BITMAP_FLAG));

  return scaledBitmap;
}

5 comments:

Anonymous said...

Thank you...solved a big problem

Anonymous said...

THANK YOU SIR! THANK YOU!

Anonymous said...

Oh Man thanks alot

永成 said...

what value should I assign to newWidth, and newHeight ?

adil said...

*newWidth* and *newHeight* is the width and height that you want the scaled Bitmap to have.