用python, PIL在图像上添加文字(可以控制,调节为水印等)

  • 最近想在图像上,添加想要的文字,首先想到的是matplotlib,但是这个更加倾向于画图(柱状图,折线图之类)
  • opencv这个库肯定也行,但是为了和我现有程序连接在一起,我选择了PIL
  • 其中字体的设置,具体看自己系统里面有哪个字体,不过可以自己设置一个外置字体,随程序放在一起,在代码中指定路径即可,这里是SimHei.ttf下载路径,提取码:g24h
  • 具体代码如下:
from PIL import Image, ImageDraw, ImageFont

def image_add_text(img_path, text, left, top, text_color=(255, 0, 0), text_size=13):
    img = Image.open(img_path)
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式 这里的SimHei.ttf需要有这个字体
    fontStyle = ImageFont.truetype("SimHei.ttf", text_size, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, text_color, font=fontStyle)
    return img


img_path = 'assets/1.jpg'
im = image_add_text(img_path, '这是一个测试', 50, 100, text_color=(0, 0, 0), text_size=20)
im.show()
  • 结果对比图:
    52263796209
posted @ 2019-11-02 20:14  Danno  阅读(6596)  评论(0编辑  收藏  举报