网友回复
要将多张图片拼接成九宫格(3x3 网格),可以使用 Python + Pillow 库。以下是完整的代码实现和步骤说明,支持自动调整图片大小并填充网格:
完整代码from PIL import Image
import os
def create_3x3_collage(image_paths, output_path, cell_size=(300, 300), spacing=10):
"""
将 9 张图片拼接为九宫格
:param image_paths: 图片路径列表(必须为 9 个)
:param output_path: 输出图片路径
:param cell_size: 每个格子的大小 (width, height)
:param spacing: 格子之间的间距(像素)
"""
if len(image_paths) != 9:
raise ValueError("需要 9 张图片")
# 创建画布
canvas_width = cell_size[0] * 3 + spacing * 2
canvas_height = cell_size[1] * 3 + spacing * 2
canvas = Image.new('RGB', (canvas_width, canvas_height), (255, 255, 255))
# 处理每张图片
for index, img_path in enumerate(image_paths):
row = index // 3 # 行号 (0-2)
col = index % 3 # 列号 (0-2)
# 打开图片并调整大小(强制填充)
img = Image.open(img_path)
img = img.resize(cell_size, Image.Resampling.LANCZOS) # 使用高质量缩放
# 计算粘贴位置
x = col * (cell_size[0] + spacing)
y = row * (cell_size[1] + spacing)
canvas.paste(i...点击查看剩余70%


