Merge Images in Python with PIL: Step-by-Step
In Python, you can use the PIL library (Pillow) to combine multiple images into one image. Here is an example code:
from PIL import Image
# 打开多个图像文件
image1 = Image.open('image1.jpg')
image2 = Image.open('image2.jpg')
image3 = Image.open('image3.jpg')
# 获取每个图像文件的大小
width1, height1 = image1.size
width2, height2 = image2.size
width3, height3 = image3.size
# 创建一张新的空白图像
new_width = width1 + width2 + width3
new_height = max(height1, height2, height3)
new_image = Image.new('RGB', (new_width, new_height), (255, 255, 255))
# 将每个图像文件粘贴到新的图像文件中
new_image.paste(image1, (0, 0))
new_image.paste(image2, (width1, 0))
new_image.paste(image3, (width1 + width2, 0))
# 保存合并后的图像文件
new_image.save('merged_image.jpg')
In the sample code above, multiple image files are first opened, then the size of each file is obtained. Next, a new blank image is created, and each image file is pasted into the new image. Finally, the merged image file is saved. You can adjust the file names and locations in the code as needed to meet your requirements.