import os
from math import ceil, sqrt
from PIL import Image
import random

# 设置图片文件夹路径
folder_path = 'output2'
output_folder = 'output3'
output_path = 'output3/merged_image.png'

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 获取所有 PNG 文件
images = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.lower().endswith('.png')]
if not images:
    print("没有找到 PNG 图片。")
    exit()

random.shuffle(images)

num_images = len(images)
# 计算行数和列数，使得接近正方形
cols = ceil(sqrt(num_images))
rows = ceil(num_images / cols)

# 打开所有图片并获取尺寸
opened_images = [Image.open(img) for img in images]
widths, heights = zip(*(img.size for img in opened_images))

# 假设所有图片尺寸相同，如果不同，可以选择调整大小
max_width = max(widths)
max_height = max(heights)

# 创建一个新的空白图片
merged_width = cols * max_width
merged_height = rows * max_height
merged_image = Image.new('RGBA', (merged_width, merged_height), (255, 255, 255, 0))

# 将每张图片粘贴到合适的位置
for index, img in enumerate(opened_images):
    row = index // cols
    col = index % cols
    x = col * max_width
    y = row * max_height
    merged_image.paste(img, (x, y))

# 保存合并后的图片
merged_image.save(output_path)
print(f"图片已成功合并并保存为 {output_path}")
