5

python3使用PIL添加中文文本水印背景 - Mike_Zhang

 1 year ago
source link: https://www.cnblogs.com/MikeZhang/p/pyWatermaker20230704.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
环境:Windows10_x64 
Python版本 :3.9.2
Pillow版本:9.1.1
写的博客文章被转载且不注明出处的情况时有发生,甚至有部分转载者将文章配图添加自己的水印!为了保护作者劳动成果,添加水印是一个可选项。
今天记录下Windows10环境下使用python3.9简单实现批量添加中文文本水印背景的过程,并提供示例代码及相关资源下载,可从如下渠道获取:
关注微信公众号(聊聊博文,文末可扫码)后回复 20230704 获取。 

一、背景描述

python的PIL库可进行图片处理,十分强大,可使用该库实现图片添加水印背景的需求。
可通过pip进行安装(默认安装最新版),命令如下:
pip install Pillow 

pypi地址: https://pypi.org/project/Pillow/

300959-20230705002510542-826087384.png
300959-20230705002521901-362948154.png

二、具体实现

这里列举下实现文本水印背景的关键点。

1、生成文本背景

可通过ImageDraw.text实现:
300959-20230705002620947-1994830044.png
中文文本可通过设置正确的字体实现:
font = ImageFont.truetype("simsun.ttc", fontSize,encoding="utf-8")
文本颜色可通过RGB值设置,示例如下:
fill=(106,106,106)

2、旋转文本

 可通过rotate函数实现:
300959-20230705002731433-604838525.png

 3、设置水印

可通过Image.paste函数实现:
300959-20230705002747720-13754507.png

 4、生成水印背景

1)需要通过循环控制,多次设置背景图片;
i,j = 0,0
while True:
    x,y = i*step,i*step
    if y < height : 
        x = 0
    if y > height : 
        x = j*step
        j = j + 1
        y = height - 10
    #print(i,"xy :",x,y)
    draw_text(img,(x,y),fill,mask,rotated_mask)
    if (x + step > width ) and (y + step > height ) : break
    i = i + 1
2)导出时需要添加质量参数,避免导出的图片失真;
img.save(dstFile,optimize=True, quality=100)

5、多进程加速

批量添加文本水印背景时,可使用进程池进行加速。
pool = Pool(processes=8)    # set the processes max number 
for root, dirs, files in os.walk(srcDir):
    for name in files:
        srcFile = os.path.join(root, name)
        dstFile = os.path.join(dstDir, name)
        print("%s => %s" % (srcFile,dstFile))
        # add_watermark(srcFile,dstFile,fontSize,myText,angle,fill,step)
        result = pool.apply_async(add_watermark,(srcFile,dstFile,fontSize,myText,angle,fill,step))
pool.close()
pool.join()  
完整源码可以从如下途径获取:
关注微信公众号(聊聊博文,文末可扫码)后回复 20230704 获取。 

三、运行效果

这里演示下python3使用PIL添加中文文本水印背景的运行效果,具体如下:
300959-20230705003056263-1678884682.png

 运行效果演示视频获取途径:

关注微信公众号(聊聊博文,文末可扫码)后回复 2023070401 获取。 

四、资源下载

本文涉及源码和文件,可以从如下途径获取:
关注微信公众号(聊聊博文,文末可扫码)后回复 20230704 获取。 
300959-20230705003122441-1781623850.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK