Is there any way to resize a Bitmap without distortion so that it does not exceed 720*1280 ? Smaller height and width is completely fine (blank canvas in case of smaller width or height is fine) I tried this https://stackoverflow.com/a/15441311/6848469 but it gives distorted image. Can anybody suggest a better solution?
Asked
Active
Viewed 3,877 times
1
-
@pskink resized Bitmap – Dinesh Neupane Jan 02 '18 at 07:38
-
@pskink gives distorted image... i want to scale the bitmap without distorting (maintaining aspect ratio or uniform scaling ) and set it to a canvas of size 720*1280 – Dinesh Neupane Jan 02 '18 at 08:09
-
@pskink can you please answer how to scale a Bitmap of any size uniformly so that id does not exceed specified height and width? – Dinesh Neupane Jan 02 '18 at 08:22
1 Answers
4
Here is the method for downscaling bitmap not to exceed MAX_ALLOWED_RESOLUTION. In you case MAX_ALLOWED_RESOLUTION = 1280
. It will downscale without any distortion and losing quality:
private static Bitmap downscaleToMaxAllowedDimension(String photoPath) {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoPath, bitmapOptions);
int srcWidth = bitmapOptions.outWidth;
int srcHeight = bitmapOptions.outHeight;
int dstWidth = srcWidth;
float scale = (float) srcWidth / srcHeight;
if (srcWidth > srcHeight && srcWidth > MAX_ALLOWED_RESOLUTION) {
dstWidth = MAX_ALLOWED_RESOLUTION;
} else if (srcHeight > srcWidth && srcHeight > MAX_ALLOWED_RESOLUTION) {
dstWidth = (int) (MAX_ALLOWED_RESOLUTION * scale);
}
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inDensity = bitmapOptions.outWidth;
bitmapOptions.inTargetDensity = dstWidth;
return BitmapFactory.decodeFile(photoPath, bitmapOptions);
}
In case if you already have BITMAP object and not path use this:
private static Bitmap downscaleToMaxAllowedDimension(Bitmap bitmap) {
int MAX_ALLOWED_RESOLUTION = 1024;
int outWidth;
int outHeight;
int inWidth = bitmap.getWidth();
int inHeight = bitmap.getHeight();
if(inWidth > inHeight){
outWidth = MAX_ALLOWED_RESOLUTION;
outHeight = (inHeight * MAX_ALLOWED_RESOLUTION) / inWidth;
} else {
outHeight = MAX_ALLOWED_RESOLUTION;
outWidth = (inWidth * MAX_ALLOWED_RESOLUTION) / inHeight;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, outWidth, outHeight, false);
return resizedBitmap;
}

Misha Akopov
- 12,241
- 27
- 68
- 82