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;
}

10 comments:

Anonymous said...

Thank you...solved a big problem

Anonymous said...

THANK YOU SIR! THANK YOU!

Anonymous said...

Oh Man thanks alot

tony 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.

Anonymous said...

image quality is poor using this method, why so?

adil said...

Anonymous, I'm not sure why you're seeing poor image quality. It was a long time ago that I used this method but when I did I had good results with it.

Azam said...

That's great. Thanks a lot for saving my time. :))

Su said...

Can I use my original canvas by using
public static Bitmap scaleBitmap(Bitmap bitmap, int newWidth, int newHeight, Canvas canvas)?
Thank you very much for your time in advance.

Anonymous said...

You're the best

Thank you so much for the share