在Python中将“垂直”图像转换为“水平”图像

问题描述

我在Python中遇到问题。我希望通过用彩色(例如:白色)填充边框,将“垂直”图像的尺寸调整为1920 * 1080p。

说明:

我想要一张像 this one

要转换成类似this one图片

我用枕头来尝试一些东西,但是没有什么决定性的事情发生。

您能帮我吗?非常感谢你 ! :)

解决方法

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

  • 使用 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,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,0))
im_2.save('approach_2.png')

两者都创建了这样的图像:

Output

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
Pillow:      8.1.0
----------------------------------------