Python实现图片加水印

为了防止博客被爬,本站的所有文章的图片都添加水印。前几天刚刚学习完python,拿来练练手,确实有很多不熟悉的类库和代码,权当试试水了。。

#! /usr/bin/python
# coding:utf-8 
import os
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import random

def Watermark(fname, text):
    # 设置字体
    font = ImageFont.truetype("STLITI.TTF", 25)  # 不同的电脑可能不存在这里的字体,导致最后没有输出结果;如果你的电脑上没有这几种字体,请自行修改

    # 实例化图片对象
    imageFile = fname
    img = Image.open(imageFile).convert('RGBA')
    text_overlay=Image.new("RGBA",img.size,(255,255,255,0))
    draw = ImageDraw.Draw(text_overlay)

    t=max(text)
    t_len=len(t)

    for i in range(0, img.size[0], t_len*20+100):
        for j in range(0, img.size[1], t_len*20):
            draw.text((i, j), random.choice(text), font=font, fill=(0, 0, 0, 50))

    text_overlay = text_overlay.rotate(45)
    image_with_text = Image.alpha_composite(img, text_overlay)
    # 另存图片
    image_with_text.save("{}_marked.png".format(fname.split(".")[0]))



def drawText(path,text):
    if not os.path.exists(path):
        print("没有这个路径:",path)
    fileList= [os.path.join(fpathe,f) for fpathe,dirs,fs in os.walk(path) for f in fs if f.split(".")[1] in ["png","jpg"] and not f.split(".")[0][-6:]=="marked"]
    for img in fileList:
        Watermark(img,text)


if __name__ == '__main__':

    path="root"
    drawText(path,["text1","text2"])

本站的图片加水印对比效果:
tensorflow{:height=”600px” width=”600px”}
tensorflow{:height=”600px” width=”600px”}