给图片添加文字(水印)方法python代码

素材:名单f.xlsx
序号 校区 姓名 电话 部门 职位
351 上海普陀校区 曾志鹏 19307130192 咨询部 咨询
352 杭州西湖校区 陈泽祥 19300180069 办公室 校长
353 杭州西湖校区 戴子瑜 19300180001 教学部 教学经理
354 杭州西湖校区 杜心怡 19300180142 咨询部 咨询经理
355 北京中关村校区 葛明坤 19300180051 办公室 校长
356 北京中关村校区 郭家成 19300180034 咨询 咨询顾问
357 北京中关村校区 胡海辰 18307110233 教学部 教学经理
358 石家庄校区 蒋超源 19307130014 办公室 校长
359 石家庄校区 金雍奇 19300180057 咨询部 咨询经理
360 石家庄校区 邝 麒 19300180102 教学部 讲师
361 深圳宝安校区 李泽昊 19300180070 办公室 校长
362 深圳宝安校区 厉 茗 19300180127 教学部 教学经理
363 深圳宝安校区 吕文韬 19300180079 咨询部 咨询顾问
364 成都天府校区 马 赫 19300180067 办公室 校长
365 成都天府校区 宋明奇 19307110261 咨询部 咨询经理
366 成都天府校区 吴家茂 19300180082 教学部 教学经理
367 西安碑林校区 吴 强 19300180083 办公室 校长
368 西安碑林校区 肖云洋 19307110356 咨询部 咨询顾问

图片素材 src.jpg

  • 命令行安装运行需要的依赖包:pip install pillow openpyxl
  • python源代码:
#运行环境:win11、python 3.11
from PIL import Image, ImageDraw, ImageFont
from openpyxl import load_workbook
import random


def task(username, userinfo):
    image = Image.open("./src.jpg")
    draw = ImageDraw.Draw(image)
    color = 'black'
    text = str(username)
    size = 34
    font = ImageFont.truetype(r"C:\Windows\Fonts\STXINWEI.ttf", size=size)
    text_width = draw.textlength(text, font)
    x = (image.width - text_width) / 2
    #x=125
    y = 120
    draw.text((x, y), text, font=font, fill=color)

    text = str(userinfo)
    size = 10
    font = ImageFont.truetype(r"C:\Windows\Fonts\STXINWEI.ttf", size=size)
    text_width = draw.textlength(text, font)
    x = (image.width - text_width) / 2
    #x =120
    y = 220
    draw.text((x, y), text, font=font, fill=color)

    image.save('img/' + str(userinfo) + '-' + str(username) + '.jpg')
    #image.save('img/' + str(random.randint(100000, 999999)) + '.jpg')
    #image.show()


def import_data(file):
    workbook = load_workbook(file)
    sheet = workbook.active
    for row in sheet.iter_rows():
        row_data = [cell.value for cell in row]
        print(row_data[2])
        print(row_data[1])
        task(row_data[2], row_data[1])


if __name__ == '__main__':
    import_data(r"E:\mysite\home\f.xlsx")
    print("success")


效果图