【发布时间】:2020-10-12 14:19:26
【问题描述】:
我在 Python 中遇到了问题。我希望通过用颜色填充边框(例如:白色)将“垂直”图像调整为 1920 x 1080。
我想要一张这样的照片
要转换成这样的图片
我使用 Pillow 是为了尝试一些东西,但没有发生任何决定性的事情。
【问题讨论】:
标签: python image resize python-imaging-library photo
我在 Python 中遇到了问题。我希望通过用颜色填充边框(例如:白色)将“垂直”图像调整为 1920 x 1080。
我想要一张这样的照片
要转换成这样的图片
我使用 Pillow 是为了尝试一些东西,但没有发生任何决定性的事情。
【问题讨论】:
标签: python image resize python-imaging-library photo
一般的管道是将输入图像的大小调整到所需的高度,同时保持纵横比。您需要根据调整后的输入图像的目标宽度和当前宽度来确定必要边框的大小。那么,两种方法可能适用:
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
----------------------------------------
【讨论】: