首页 > 解决方案 > 枕头调整图像大小 - 保持纵横比

问题描述

我有以下示例,我希望使用 Pillow 调整图像大小。

如您所见,我有一个新的宽度由用户传入,但没有高度。在保持相同纵横比的同时,我如何计算出这张图片的新高度?

图像不是正方形,它们是矩形,因此高度和宽度不会相同。

    orig_image = Image.open(get_full_path(file.relative_path))
    new_width = int(request.args.get('w'))

    # TODO resize properly, we need to work out new image height
    resized_image = orig_image.resize((new_width, ), Image.ANTIALIAS)

标签: pythonpython-imaging-library

解决方案


听起来您想从原始图像中获取原始纵横比,如下所示:

aspect_ratio = orgin_image.width / orgin_image.height

一旦你收到了new_width你就可以new_height这样计算:

new_height = new_width * aspect_ratio

然后您可以正确调整图像大小:

resized_image = orig_image.resize((new_width, new_height), Image.ANTIALIAS)

或者把它们放在一起:

orig_image = Image.open(get_full_path(file.relative_path))
aspect_ratio = orgin_image.width / organ_image.height

new_width = int(request.args.get('w'))
new_height = new_width * aspect_ratio

resized_image = orig_image.resize((new_width, new_height), Image.ANTIALIAS)

推荐阅读