python - 枕头调整图像大小 - 保持纵横比
问题描述
我有以下示例,我希望使用 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)
解决方案
听起来您想从原始图像中获取原始纵横比,如下所示:
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)
推荐阅读
- android - 应用未运行时在 Android Oreo 中未收到通知
- javascript - 使用 Protractor 和 VSTS 管道 (JavaScript) 最大化 Chrome
- tsql - 查找用户定义的数据库角色具有哪些权限
- machine-learning - Keras 中的 initial_epoch 是什么意思?
- ios - navigationItem 上的 UIImageView 尺寸错误
- html - 表体中的定心跨度
- mysql - 日期之间的sql查询不拾取行
- sql - SSMS - 删除重复的分组值
- swift - 地理编码地址不提供纬度和经度
- twig - 如何在 Twig 中执行 foreach 循环