说明:给指定图片添加指定文本的水印

from PIL import Image,ImageDraw,ImageFont
import base64,time

def imgToBase64(image_path,string="发生异常-11"):
    print("图片地址: "+image_path+",正在添加水印---")
    try:
        oriImg = Image.open(image_path)
        addText(oriImg,image_path,string)
    except:
        print(image_path+"图片添加水印失败---")
        
    # time.sleep(1)
    with open(image_path, 'rb') as f:
        image = f.read()
        image_base64 = "data:image/png;base64,"+str(base64.b64encode(image), encoding='utf-8')
        print(image_base64)

#图片加水印显示错误信息
def addText(oriImg,path,string):
    fontpath = "font/kt.ttf" # 64为字体大小
    font = ImageFont.truetype(fontpath, 64)
    draw = ImageDraw.Draw(oriImg)
    draw.text(xy=(50,50),text=string,fill='red',font=font)
    # oriImg.show()
    oriImg.save(path)

path = "J:\\Users\\username\\Pictures\\壁纸\\test.png"
imgToBase64(path,"HelloWorld")
最后修改:2023 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏