多张图片拼合为一张,如何实现?

12 min read

此需求可以通过使用Python的PIL库来实现。

以下是示例代码:

from PIL import Image

# 创建一个包含所有图像的列表
image_list = ['image1.jpg', 'image2.jpg', 'image3.jpg']

# 打开每张图像,并获取宽度和高度作为新图像的大小
new_image_width = 0
new_image_height = 0
images = []
for img_path in image_list:
    img = Image.open(img_path)
    images.append(img)
    new_image_width += img.size[0]
    new_image_height = max(new_image_height, img.size[1])

# 创建一个新的空图像
new_image = Image.new('RGBA', (new_image_width, new_image_height))

# 将每张图像添加到新图像中
x_offset = 0
for img in images:
    new_image.paste(img, (x_offset, 0))
    x_offset += img.size[0]

# 保存合成后的图像
new_image.save('combined_image.jpg')

以上代码将创建一个新的图像,将输入的所有图像水平排列在一起,并保存合成后的图像。