from PIL import Image
def concatenate_images(image_paths, direction='horizontal'):
"""
将多张图片拼接成一张图片。
参数:
image_paths (list): 包含图片路径的列表。
direction (str): 拼接方向,'horizontal' 或 'vertical'。
返回:
Image: 拼接后的图片。
"""
images = [Image.open(x) for x in image_paths]
widths, heights = zip(*(i.size for i in images))
if direction == 'horizontal':
total_width = sum(widths)
max_height = max(heights)
new_image = Image.new('RGB', (total_width, max_height))
x_offset = 0
for img in images:
new_image.paste(img, (x_offset, 0))
x_offset += img.size[0]
elif direction == 'vertical':
max_width = max(widths)
total_height = sum(heights)
new_image = Image.new('RGB', (max_width, total_height))
y_offset = 0
for img in images:
new_image.paste(img, (0, y_offset))
y_offset += img.size[1]
else:
raise ValueError("direction must be 'horizontal' or 'vertical'")
return new_image
# 示例用法
image_paths = ['path/to/image1.jpg', 'path/to/image2.jpg', 'path/to/image3.jpg']
concatenated_image = concatenate_images(image_paths, direction='horizontal')
concatenated_image.save('path/to/output.jpg')
from PIL import Image 导入了处理图像所需的模块。concatenate_images:该函数接受一个包含图片路径的列表,并根据指定的方向(水平或垂直)将这些图片拼接在一起。image_paths:包含图片路径的列表。direction:指定拼接方向,默认为水平拼接。concatenate_images 函数并将结果保存到指定路径。如果你有任何问题或需要进一步的帮助,请告诉我!
上一篇:python translate
下一篇:python中列表的概念
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站