首页 > 解决方案 > 如何将“垂直”图像转换为“水平”图像?

问题描述

我在 Python 中遇到了一个问题。我希望1920 x 1080通过用颜色(例如:白色)填充边框来调整“垂直”图像的大小。

我想要一张这样的照片

输入

转换成这样的图片

期望的输出

我使用 Pillow 来尝试一些东西,但没有发生任何决定性的事情。

标签: pythonimageresizepython-imaging-libraryphoto

解决方案


一般管道是将输入图像的大小调整到所需的高度,同时保持纵横比。您需要根据调整后的输入图像的目标宽度和当前宽度来确定必要边框的大小。然后,两种方法可能适用:

  • 要么使用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
----------------------------------------

推荐阅读