调整位图的大小,保持宽高比,不会出现失真和裁剪

问题描述 投票:0回答:1

有没有办法在没有失真的情况下调整Bitmap的大小,使其不超过720 * 1280?较小的高度和宽度是完全正常的(如果宽度或高度较小的情况下空白画布很好)我尝试了这个https://stackoverflow.com/a/15441311/6848469但它给出了扭曲的图像。任何人都能提出更好的解决方案吗?

android bitmap android-imageview android-bitmap
1个回答
1
投票

以下是缩放位图不超过MAX_ALLOWED_RESOLUTION的方法。在你的情况下MAX_ALLOWED_RESOLUTION = 1280。它将缩小尺寸而不会出现任何失真和质量下降:

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

如果你已经有BITMAP对象而不是路径,请使用:

 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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.