调整位图大小保持纵横比,不失真和裁剪



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

这是缩小位图不超过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);
}

如果您已经有位图对象而不是路径,请使用以下命令:

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

最新更新