我的知识记录

Python 在图片上批量添加文字 水印标题教程

用 Pillow 批量在图片固定位置加中文文字,支持自定义字体、字号、颜色、描边、居左居右居上居下,适合给商品图、活动图、公告图批量打标题。

场景痛点

活动方图每张都要加标题,比如"夏日促销 全场5折",设计稿换十句文案就要出十张图,一张张 PS 打字对齐太慢。用 Python 把文案写进一个列表,循环套到同一张模板上,自动居中、自动换行,几秒出一整套图。

用到的库

pip install Pillow

完整代码

# -*- coding: utf-8 -*-
# 批量在图片指定位置写中文文字,带描边,支持多行
import os
from PIL import Image, ImageDraw, ImageFont

IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
# Windows: C:/Windows/Fonts/msyhbd.ttc (微软雅黑粗体)

def draw_text_with_outline(draw, xy, text, font,
fill=(255, 255, 255),
outline=(0, 0, 0), ow=2):
"""在 draw 上画带描边的文字,避免浅色图上看不清"""
x, y = xy
for dx in (-ow, 0, ow):
for dy in (-ow, 0, ow):
if dx == 0 and dy == 0:
continue
draw.text((x + dx, y + dy), text, font=font, fill=outline)
draw.text((x, y), text, font=font, fill=fill)

def add_text_centered(im, text, font_size=48, position="bottom",
fill=(255, 255, 255)):
"""在图片上中下位置居中写文字"""
im = im.convert("RGBA")
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(FONT_PATH, font_size)
bbox = draw.textbbox((0, 0), text, font=font)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]

x = (im.width - tw) // 2
if position == "top":
y = 20
elif position == "center":
y = (im.height - th) // 2
else:  # bottom
y = im.height - th - 40

draw_text_with_outline(draw, (x - bbox[0], y - bbox[1]),
text, font, fill=fill)
return im.convert("RGB")

def batch_add_text(input_dir, output_dir, texts):
"""texts 是和文件名一一对应的文案列表,或同一句"""
os.makedirs(output_dir, exist_ok=True)
files = sorted(f for f in os.listdir(input_dir)
if os.path.splitext(f)[1].lower() in IMG_EXTS)
for i, name in enumerate(files):
text = texts[i] if isinstance(texts, list) else texts
with Image.open(os.path.join(input_dir, name)) as im:
out = add_text_centered(im, text, font_size=48,
position="bottom")
out.save(os.path.join(output_dir, name), quality=92)
print(f"加文字 {text}  -> {name}")

if __name__ == "__main__":
# 模板图同一句话加文字
batch_add_text("./tpl", "./out", "夏日促销 全场5折")

代码讲解

  • ImageDraw.Draw(im) 拿到画笔,draw.text((x,y), text, font=font, fill=颜色) 就是最基本的写文字。
  • 中文必须用 truetype 加载字体文件,默认位图字体不支持中文,会出方框。
  • textbbox 量出文字真实宽高,再算 (im.width - tw)/2 实现水平居中,比凭感觉调坐标准得多。
  • draw_text_with_outline 通过在文字四周 8 个方向偏移 2px 画黑色,再在中间画白色,做出描边效果,浅色背景上也看得清。
  • position 支持 top/center/bottom,常用的就是底部加标题。

运行结果

把模板图放进 ./tpl,运行后 ./out 里得到同名图,底部居中一行白色带黑边的"夏日促销 全场5折"。把 texts 传成 ["文案A","文案B","文案C"] 列表,就能按文件顺序批量套不同标题。

注意事项

  • 字体路径必须存在,Windows 上微软雅黑是 C:/Windows/Fonts/msyh.ttc,粗体是 msyhbd.ttc
  • 长标题超出图片宽度时不会自动换行,需要手动 \n 分段,或自己按像素宽度断行。
  • 输出 JPG 时先 convert("RGB"),否则透明合成会出问题。
  • 描边宽度 ow 别超过字号的 1/10,不然字会变胖。

Python 在图片上批量添加文字 水印标题教程

标签:

更新时间:2026-09-14 20:24:09

上一篇:Python 两张图片对比找差异 高亮不同区域教程

下一篇:Python 批量生成水印 PDF 与图片混合文档教程