动态计算拼接图片大小
from PIL import Image
import os
# 定义图片文件夹路径
folder_path = "images/"
# 获取图片文件名列表
image_files = [filename for filename in os.listdir(folder_path) if filename.endswith('.png')]
# 存储图片对象的列表
images = []
# 读取图片并添加到列表中
for filename in image_files:
image = Image.open(os.path.join(folder_path, filename))
images.append(image)
# 获取第一张图片的大小
width, height = images[0].size
# 计算拼接图片的行数和列数
num_images = len(images)
num_rows = (num_images + 1) // 2
num_cols = 2
# 创建一个新的大图,用于拼接图片
result_width = num_cols * width
result_height = num_rows * height
result_image = Image.new("RGB", (result_width, result_height))
# 拼接图片
for i in range(num_rows):
for j in range(num_cols):
index = i * num_cols + j
if index < num_images:
result_image.paste(images[index], (j * width, i * height))
# 保存拼接后的图片
result_image.save("result_image.png")
# 显示拼接后的图片
result_image.show()