python3使用PIL添加中文文本水印背景方法詳解
環(huán)境:Windows10_x64
Python版本 :3.9.2
Pillow版本:9.1.1
寫的博客文章被轉載且不注明出處的情況時有發(fā)生,甚至有部分轉載者將文章配圖添加自己的水??!為了保護作者勞動成果,添加水印是一個可選項。
今天記錄下Windows10環(huán)境下使用python3.9簡單實現(xiàn)批量添加中文文本水印背景的過程,并提供示例代碼
一、背景描述
python的PIL庫可進行圖片處理,十分強大,可使用該庫實現(xiàn)圖片添加水印背景的需求。
可通過pip進行安裝(默認安裝最新版),命令如下:
pip install Pillow
pypi地址: https://pypi.org/project/Pillow/
文檔地址: https://pillow.readthedocs.io/en/stable/
二、具體實現(xiàn)
這里列舉下實現(xiàn)文本水印背景的關鍵點。
1、生成文本背景
可通過ImageDraw.text實現(xiàn):
https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html
中文文本可通過設置正確的字體實現(xiàn):
font = ImageFont.truetype("simsun.ttc", fontSize,encoding="utf-8")
文本顏色可通過RGB值設置,示例如下:
fill=(106,106,106)
2、旋轉文本
可通過rotate函數(shù)實現(xiàn):
https://pillow.readthedocs.io/en/stable/reference/Image.html
3、設置水印
可通過Image.paste函數(shù)實現(xiàn):
https://pillow.readthedocs.io/en/stable/reference/Image.html
4、生成水印背景
1)需要通過循環(huán)控制,多次設置背景圖片;
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)導出時需要添加質量參數(shù),避免導出的圖片失真;
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()
三、運行效果
這里演示下python3使用PIL添加中文文本水印背景的運行效果,具體如下:
四、資源下載
到此這篇關于python3使用PIL添加中文文本水印背景方法詳解的文章就介紹到這了,更多相關python3使用PIL添加水印背景內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決usageerror: line magic function "
這篇文章主要介紹了解決usageerror: line magic function "%%time" not found問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01python數(shù)學建模之Matplotlib?實現(xiàn)圖片繪制
這篇文章主要介紹了python數(shù)學建模之Matplotlib?實現(xiàn)圖片繪制,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07Python+mpld3實現(xiàn)交互式Matplotlib圖表
通過結合使用Matplotlib和mpld3庫,我們可以輕松地創(chuàng)建交互式圖表,使得數(shù)據(jù)可視化更加生動和易于理解,下面就跟隨小編一起來學習一下具體實現(xiàn)方法吧2024-10-10python numpy之np.random的隨機數(shù)函數(shù)使用介紹
這篇文章主要介紹了python numpy之np.random的隨機數(shù)函數(shù)使用介紹,需要的朋友可以參考下2019-10-10使用python BeautifulSoup庫抓取58手機維修信息
這篇文章主要介紹了一個使用python抓取58手機的精準商家信息,使用BeautifulSoup API的方法2013-11-11淺談numpy中函數(shù)resize與reshape,ravel與flatten的區(qū)別
這篇文章主要介紹了淺談numpy中函數(shù)resize與reshape,ravel與flatten的區(qū)別介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06