1

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?

Dinesh Neupane
  • 382
  • 10
  • 19

1 Answers1

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