调整位图大小保持纵横比且不变形和裁剪

Din*_*ane 1 android bitmap android-imageview android-bitmap

有没有办法在不变形的情况下调整位图大小,使其不超过 720*1280 ?较小的高度和宽度完全没问题(在较小宽度或高度的情况下空白画布很好)我尝试了这个/sf/answers/1080891801/,但它给出了扭曲的图像。有人能提出更好的解决方案吗?

Mis*_*pov 5

这是缩小位图不超过 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);
}
Run Code Online (Sandbox Code Playgroud)

如果您已经有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;
    }
Run Code Online (Sandbox Code Playgroud)