+
67
-

回答

要将多张图片拼接成九宫格(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(img, (x, y))

    canvas.save(output_path)
    print(f"九宫格已保存至 {output_path}")

# 示例用法
if __name__ == "__main__":
    # 替换为你的图片路径列表(按顺序排列)
    image_files = [
        "image1.jpg", "image2.jpg", "image3.jpg",
        "image4.jpg", "image5.jpg", "image6.jpg",
        "image7.jpg", "image8.jpg", "image9.jpg"
    ]

    create_3x3_collage(
        image_files,
        output_path="collage.jpg",
        cell_size=(300, 300),  # 每个格子大小
        spacing=10             # 间距
    )
关键步骤说明

准备图片

确保图片路径列表 image_paths 包含 9 张图片。图片顺序按行排列:第一行前 3 张,第二行中间 3 张,第三行最后 3 张。

调整图片尺寸

img = img.resize(cell_size, Image.Resampling.LANCZOS)
使用 resize 强制将每张图片缩放到 cell_size 大小(默认 300x300)。LANCZOS 算法确保缩放质量。

计算位置

行号:row = index // 3列号:col = index % 3坐标公式
x = col * (cell_size[0] + spacing)
y = row * (cell_size[1] + spacing)

画布尺寸

canvas_width = cell_size[0] * 3 + spacing * 2
canvas_height = cell_size[1] * 3 + spacing * 2
总宽度 = 单格宽度 × 3 + 间距 × 2(如 300*3 + 10*2 = 920px)效果优化1. 保持图片比例(避免拉伸)
   # 替换 resize 部分
   img = Image.open(img_path)
   img.thumbnail((cell_size[0], cell_size[1]), Image.Resampling.LANCZOS)  # 保持比例
   bg = Image.new('RGB', cell_size, (255, 255, 255))  # 创建白色背景
   bg.paste(img, ((cell_size[0] - img.width) // 2, (cell_size[1] - img.height) // 2))  # 居中粘贴
   img = bg
用 thumbnail 保持原图比例,居中放置在白色背景上。2. 添加圆角或边框
   from PIL import ImageDraw

   # 添加圆角
   def add_rounded_corners(img, radius=20):
       mask = Image.new('L', img.size, 0)
       draw = ImageDraw.Draw(mask)
       draw.rounded_rectangle([(0, 0), img.size], radius, fill=255)
       img.putalpha(mask)
       return img

   img = add_rounded_corners(img)
3. 自动填充不足 9 张图片
   if len(image_paths) < 9:
       # 用空白图片补足
       blank = Image.new('RGB', cell_size, (200, 200, 200))
       image_paths += [blank] * (9 - len(image_paths))
运行示例

假设图片按顺序排列:

输入图片顺序:
1 2 3
4 5 6
7 8 9

输出效果:
┌───────┬───────┬───────┐
│   1   │   2   │   3   │
├───────┼───────┼───────┤
│   4   │   5   │   6   │
├───────┼───────┼───────┤
│   7   │   8   │   9   │
└───────┴───────┴───────┘
环境依赖安装 Pillow 库:
pip install Pillow
支持的图片格式:JPEG、PNG、BMP 等。

网友回复

我知道答案,我要回答