I\'m looking for a solution for the following problem: how to change the size of a Bitmap
to a fixed size (for example 512x128). The aspect ratio of the bitmap conte
I think @Coen's answer is not right solution for this question. I also needed a method like this but I wanted to square image.
Here is my solution for square image;
public static Bitmap resizeBitmapImageForFitSquare(Bitmap image, int maxResolution) {
if (maxResolution <= 0)
return image;
int width = image.getWidth();
int height = image.getHeight();
float ratio = (width >= height) ? (float)maxResolution/width :(float)maxResolution/height;
int finalWidth = (int) ((float)width * ratio);
int finalHeight = (int) ((float)height * ratio);
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
if (image.getWidth() == image.getHeight())
return image;
else {
//fit height and width
int left = 0;
int top = 0;
if(image.getWidth() != maxResolution)
left = (maxResolution - image.getWidth()) / 2;
if(image.getHeight() != maxResolution)
top = (maxResolution - image.getHeight()) / 2;
Bitmap bitmap = Bitmap.createBitmap(maxResolution, maxResolution, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(image, left, top, null);
canvas.save();
canvas.restore();
return bitmap;
}
}