How can Python combine two images into one?
Here is an example code in Python that demonstrates how to merge two images using the PIL library (Pillow).
from PIL import Image
# 打开两张图片
image1 = Image.open('image1.jpg')
image2 = Image.open('image2.jpg')
# 获取图片的宽度和高度
width1, height1 = image1.size
width2, height2 = image2.size
# 创建新的图片,宽度为两张图片的宽度之和,高度为两张图片中高度较大的一个
new_width = width1 + width2
new_height = max(height1, height2)
new_image = Image.new('RGB', (new_width, new_height))
# 将第一张图片粘贴到左上角
new_image.paste(image1, (0, 0))
# 将第二张图片粘贴到第一张图片的右边
new_image.paste(image2, (width1, 0))
# 保存合并后的图片
new_image.save('merged_image.jpg')
In the code above, image1.jpg and image2.jpg are the two images to be merged. The code first opens the two images, then gets their widths and heights. Next, it creates a new image with a width equal to the sum of the widths of the two images, and a height equal to the greater of the heights of the two images. Then, it pastes the first image into the top left corner of the new image, and pastes the second image to the right of the first image. Finally, it saves the merged image as merged_image.jpg.