2025-07-21 18:47:59 +08:00

71 lines
2.3 KiB
Python

from PIL import Image, ImageDraw, ImageFont
import math
def generate_image_grid(images, titles, output_path, small_width=200, small_height=200, caption_height=30, max_per_row=5):
num_images = len(images)
# 参数检查
if num_images > 10:
raise ValueError("最多十张图片")
if num_images != len(titles):
raise ValueError("图片和标题数量必须一致")
# 计算行数
rows = math.ceil(num_images / max_per_row)
# 创建大图
total_width = max_per_row * small_width
total_height = rows * (small_height + caption_height)
grid_image = Image.new('RGB', (total_width, total_height), color=(255, 255, 255))
draw = ImageDraw.Draw(grid_image)
# 加载字体(尝试使用系统字体,否则使用默认字体)
try:
font = ImageFont.truetype("arial.ttf", 16)
except:
font = ImageFont.load_default()
# 拼接图片并添加标题
for i in range(num_images):
row = i // max_per_row
col = i % max_per_row
x = col * small_width
y = row * (small_height + caption_height)
# 调整图片大小并粘贴
img = images[i].resize((small_width, small_height))
grid_image.paste(img, (x, y))
# 绘制标题
caption = titles[i]
text_width, text_height = font.getsize(caption)
text_x = x + (small_width - text_width) // 2
text_y = y + small_height + (caption_height - text_height) // 2
draw.text((text_x, text_y), caption, fill=(0, 0, 0), font=font)
# 保存结果
grid_image.save(output_path)
def create_test_images(n, size=(200, 200)):
colors = ['red', 'green', 'blue', 'yellow', 'cyan',
'magenta', 'black', 'white', 'orange', 'purple']
images = []
for i in range(n):
img = Image.new('RGB', size, color=colors[i % len(colors)])
draw = ImageDraw.Draw(img)
draw.text((10, 10), f"Image {i+1}", fill=(255, 255, 255), font=ImageFont.load_default())
images.append(img)
return images
# 示例调用
if __name__ == "__main__":
# 生成 7 张测试图片
test_images = create_test_images(7)
# 设置标题
titles = [f"Title {i+1}" for i in range(7)]
# 拼接图片并保存
generate_image_grid(test_images, titles, 'grid_output.png')