Python 批量拼接图片合成竖长长图教程
用 Pillow 把多张截图竖向或横向拼接成一张长图,自动对齐宽度、留间距、支持加底色,适合聊天记录、海报组图、代码截图批量合成。
场景痛点
做教程时要把十几张截图拼成一张长图发朋友圈或写文档,用截图工具一张张拖,对齐宽度、调间距都得手动,长图导出还经常被压缩。用 Python 把一个文件夹里的图按文件名顺序自动竖向拼接,统一宽度、自动留缝、背景填白,一秒出图。
用到的库
pip install Pillow
完整代码
# -*- coding: utf-8 -*-
# 把文件夹里的图片按文件名顺序竖向拼接成一张长图
import os
from PIL import Image
IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
def vconcat_images(input_dir, out_path, target_width=1080,
gap=20, bg_color=(255, 255, 255)):
"""竖向拼接:统一缩放到 target_width,图之间留 gap 像素白缝"""
files = [f for f in sorted(os.listdir(input_dir))
if os.path.splitext(f)[1].lower() in IMG_EXTS]
if not files:
print("没有找到图片")
return
frames = []
for name in files:
with Image.open(os.path.join(input_dir, name)) as im:
im = im.convert("RGB")
# 按目标宽度等比缩放
ratio = target_width / im.width
new_h = int(im.height * ratio)
im = im.resize((target_width, new_h), Image.LANCZOS)
frames.append(im)
print(f"加载 {name} -> {target_width}x{new_h}")
total_h = sum(f.height for f in frames) + gap * (len(frames) - 1)
canvas = Image.new("RGB", (target_width, total_h), bg_color)
y = 0
for f in frames:
canvas.paste(f, (0, y))
y += f.height + gap
canvas.save(out_path, quality=92)
print(f"完成:{out_path} 尺寸 {target_width}x{total_h}")
def hconcat_images(input_dir, out_path, target_height=1080,
gap=20, bg_color=(255, 255, 255)):
"""横向拼接:统一高度,从左到右排"""
files = [f for f in sorted(os.listdir(input_dir))
if os.path.splitext(f)[1].lower() in IMG_EXTS]
frames = []
for name in files:
with Image.open(os.path.join(input_dir, name)) as im:
im = im.convert("RGB")
ratio = target_height / im.height
new_w = int(im.width * ratio)
frames.append(im.resize((new_w, target_height), Image.LANCZOS))
total_w = sum(f.width for f in frames) + gap * (len(frames) - 1)
canvas = Image.new("RGB", (total_w, target_height), bg_color)
x = 0
for f in frames:
canvas.paste(f, (x, 0))
x += f.width + gap
canvas.save(out_path, quality=92)
print(f"完成:{out_path} 尺寸 {total_w}x{target_height}")
if __name__ == "__main__":
# 把 ./shots 下的截图竖向拼成 1080 宽的长图
vconcat_images("./shots", "./long_image.jpg",
target_width=1080, gap=20)
代码讲解
- 先按文件名
sorted排序,保证拼接顺序就是资源管理器里看到的顺序;如果要自定义顺序,把文件名改成01_xxx.png这种前缀即可。 - 竖向拼接时以宽度为准等比缩放,
Image.LANCZOS是 Pillow 里质量最高的缩放算法,缩小图片不虚。 Image.new("RGB", (W, H), bg)先铺一张指定底色的画布,再用paste逐张贴上去,y 坐标累加实现竖向排列。gap控制图与图之间的留白,白底长图发朋友圈更清爽;要无缝拼接就传gap=0。- 横向拼接函数
hconcat_images同理,以高度为准缩放,x 坐标累加。
运行结果
把截图按顺序命名放进 ./shots,运行后生成 long_image.jpg,宽度统一 1080,每张图之间留 20px 白缝。打开即是一张完整长图,可直接发公众号或存云盘。
注意事项
- 图片尺寸差异大时统一缩放会让某些图变小,建议先把源图截成相近比例。
- 保存成 JPG 不支持透明通道,所以代码里统一
convert("RGB");如果要保留透明背景,输出改成.png并把模式改成"RGBA"。 - 长图高度没有硬上限,但超过 30000px 后部分看图 App 会解码失败,建议控制在 20000px 以内。
quality=92是 JPG 画质,1~95,越高文件越大。

更新时间:2026-09-14 20:23:11