使用方法是將圖片歸類到文件夾下面,如圖:
將以下內容輸入到一個文件中,放到最頂目錄隨便命名比如test.py
import os
import traceback
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
def add_text_to_image(img,root):
txt=Image.new('RGBA', img.size, (0,0,0,0))
fnt=ImageFont.truetype("DENG.TTF", 20)
d=ImageDraw.Draw(txt)
d.text((0,txt.size[1]-30), root,font=fnt, fill=(0,0,0,255))
out=Image.alpha_composite(img, txt)
sav = out.convert("RGB")
sav.save(os.path.join(root,file))
for root,dirs,files in os.walk('./'):
for file in files:
try:
img=Image.open(os.path.join(root,file)).convert('RGBA')
add_text_to_image(img,root)
except Exception as e:
print(os.path.join(root,file))
print(e)
print(traceback.format_exc())
pass
安裝依賴
pip install pillow
運行
python3 test.py
之後每張圖片有如下效果,可以做標記用: