在圖處處理之前必須Python的PIL圖像處理庫。
第一步:安裝PIL庫
打開命令窗口輸入pip install pillow等安裝結束。如圖示:
如果安裝完後出現No module named 'PIL',再安裝pip install image如下圖示:
第二步:編寫程序代碼。如以下代碼。from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import datetime #獲取當前日期和時間
import glob #找到目錄中的文件
from time import sleep #time 模塊中引入sleep函數,使用sleep函數可以推遲調用線程的運行
import time #返回當前的時間
str1 ="小羊學編程"
str2 ="python"
def add_watermark():
global i
for files in glob.glob('d:/test/*.jpg'): #返回圖片list
font = ImageFont.truetype('C:/WINDOWS/Fonts/msyh.ttf', 26) #兩個參數分別是系統字體 和字號大小
font1 = ImageFont.truetype('C:/WINDOWS/Fonts/msyh.ttf', 28)
img = Image.open(files)
i+=1
draw = ImageDraw.Draw(img)
draw.text((200,300), str1, fill=(255, 0, 0), font=font)
draw.text((350,320), str2, fill=(255, 0, 0), font=font1)
dir = "d:/test/"
name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
filename = dir + name + '.jpg'
sleep(1)
img.save(filename)
start = time.time()
i = 0
add_watermark()
c = time.time() - start
print('程序運行耗時:%0.2f'%(c))
print('總共處理了 %s 張圖片'%(i))
第三步:運行程序結果如下圖所示:
修改後的文件如圖所示: