python - 如何将“垂直”图像转换为“水平”图像?
问题描述
我在 Python 中遇到了一个问题。我希望1920 x 1080
通过用颜色(例如:白色)填充边框来调整“垂直”图像的大小。
我想要一张这样的照片
转换成这样的图片
我使用 Pillow 来尝试一些东西,但没有发生任何决定性的事情。
解决方案
一般管道是将输入图像的大小调整到所需的高度,同时保持纵横比。您需要根据调整后的输入图像的目标宽度和当前宽度来确定必要边框的大小。然后,两种方法可能适用:
- 要么使用
ImageOps.expand
直接添加所需大小和颜色的边框。 - 或者,用于
Image.new
创建具有适当目标大小和所需颜色的新图像,然后用于Image.paste
将调整大小的输入图像粘贴到该图像的适当位置。
以下是这两种方法的一些代码:
from PIL import Image, ImageOps
# Load input image
im = Image.open('path/to/your/image.jpg')
# Target size parameters
width = 1920
height = 1080
# Resize input image while keeping aspect ratio
ratio = height / im.height
im = im.resize((int(im.width * ratio), height))
# Border parameters
fill_color = (255, 255, 255)
border_l = int((width - im.width) / 2)
# Approach #1: Use ImageOps.expand()
border_r = width - im.width - border_l
im_1 = ImageOps.expand(im, (border_l, 0, border_r, 0), fill_color)
im_1.save('approach_1.png')
# Approach #2: Use Image.new() and Image.paste()
im_2 = Image.new('RGB', (width, height), fill_color)
im_2.paste(im, (border_l, 0))
im_2.save('approach_2.png')
两者都创建这样的图像:
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
Pillow: 8.1.0
----------------------------------------
推荐阅读
- javascript - 三元运算符不在反应 jsx 中呈现标记
- haskell - 获取满足条件的最短列表前缀
- javascript - 如何在条纹中保存卡片详细信息(javascript)
- python - 在Python中使用多线程下载大量文件,少数文件“滞后”
- python - Pandas 将列中的字符串替换为 int
- tensorflow - ModelCheckpoint 不保存 hdf5 文件
- flutter - 在颤动中合并视频和音频
- javascript - useEffect 不断重新渲染我的组件,尽管对象没有改变
- python - Django REST ViewSet 创建
- javascript - 使用fabric.js 免费绘图,有没有办法只在某些fabric.Objects 上进行绘制?