如何用Python在模板图片上叠加图片与文本?
Python实现模板图片叠加图片与文本方案
需要的依赖库
目前Pillow(Python Imaging Library的活跃分支)和pandas是完全可用的方案,先安装依赖:
pip install pillow pandas
核心实现步骤
1. 加载模板图片
使用Pillow打开模板图片,建议转为RGBA模式以支持透明叠加:
from PIL import Image, ImageDraw, ImageFont import pandas as pd import os # 加载模板图片,转为RGBA支持透明叠加 template_img = Image.open("template.png").convert("RGBA") template_width, template_height = template_img.size
2. 处理CSV文本数据
用pandas读取CSV,假设CSV包含text_content, x, y, font_size, font_color等字段(可根据实际结构调整):
# 读取CSV文本数据 text_df = pd.read_csv("text_data.csv") # 初始化绘图对象 draw = ImageDraw.Draw(template_img) # 遍历CSV行,添加文本 for _, row in text_df.iterrows(): text = row["text_content"] x = int(row["x"]) y = int(row["y"]) font_size = int(row["font_size"]) font_color = tuple(map(int, row["font_color"].split(","))) # 假设颜色是"255,0,0"格式 # 加载字体(可替换为本地字体路径) try: font = ImageFont.truetype("arial.ttf", font_size) except: font = ImageFont.load_default() # fallback到默认字体 # 添加文本到模板 draw.text((x, y), text, font=font, fill=font_color)
3. 处理待叠加图片文件夹
遍历指定文件夹中的图片,调整大小后叠加到模板的指定位置(这里假设图片命名包含位置信息,比如logo_100_200.png表示x=100,y=200,可根据实际规则调整):
overlay_img_dir = "overlay_images" # 遍历文件夹中的图片 for img_name in os.listdir(overlay_img_dir): if img_name.lower().endswith((".png", ".jpg", ".jpeg")): img_path = os.path.join(overlay_img_dir, img_name) overlay_img = Image.open(img_path).convert("RGBA") # 示例:从文件名提取位置(可根据实际需求自定义规则) name_parts = img_name.split("_") x = int(name_parts[1]) y = int(name_parts[2].split(".")[0]) # 调整叠加图片大小(可选,根据需求设置) # overlay_img = overlay_img.resize((100, 100)) # 叠加图片到模板 template_img.paste(overlay_img, (x, y), overlay_img) # 第三个参数是遮罩,支持透明
4. 保存最终结果
# 保存处理后的图片,转为RGB避免透明通道问题(如果不需要透明) final_img = template_img.convert("RGB") final_img.save("result.jpg")
关键注意事项
- 图片坐标:Pillow采用左上角为原点的坐标系,设置位置时要注意对应模板的实际坐标。
- 透明处理:叠加带透明通道的图片时,必须使用
convert("RGBA"),且paste方法要传入第三个遮罩参数。 - 字体问题:如果使用自定义字体,要确保字体文件路径正确,否则会 fallback 到默认字体。
- 批量处理:如果需要生成多份不同的叠加结果,可在循环中加载不同模板、CSV行或图片组合。
内容的提问来源于stack exchange,提问作者m. lekk
相关产品推荐
相关产品推荐

