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:
Thank you...solved a big problem
THANK YOU SIR! THANK YOU!
Oh Man thanks alot
what value should I assign to newWidth, and newHeight ?
*newWidth* and *newHeight* is the width and height that you want the scaled Bitmap to have.
image quality is poor using this method, why so?
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.
That's great. Thanks a lot for saving my time. :))
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.
You're the best
Thank you so much for the share
Post a Comment