利用 PIL 的图片处理库添加水印的实现.
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import os
from PIL import Image, ImageDraw, ImageFont
def add_watermark_fun1(img_pil, text):
print("[INFO]PIL image info: ", img_pil.size)
img_rgba = img_pil.convert("RGBA")
text_img = Image.new("RGBA", img_rgba.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(text_img)
font = ImageFont.truetype('NotoSansCJK-Black.ttc', 30) # 字体及字体大小
print("[INFO]Text info: ", draw.textsize(text, font=font))
text_position = (20, 20)
# 文本位置, 颜色, 透明度
draw.text(text_position, text, font=font, fill=(128, 0, 0, 50))
# 合成水印图片
img_with_watermark = Image.alpha_composite(img_rgba, text_img)
# 显示加水印后的图片
img_with_watermark.show()
return img_with_watermark.convert("RGB")
def add_watermark_fun2(img_pil, text):
print("[INFO]PIL image info: ", img_pil.size)
width, height = img_pil.width, img_pil.height
#
new_img = Image.new('RGBA', (width * 3, height * 3), (0, 0, 0, 0))
new_img.paste(img_pil, (width, height))
img_rgba = new_img.convert('RGBA')
#
text_img = Image.new('RGBA', img_rgba.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(text_img)
# 添加水印
# 文本位置, 颜色, 透明度
font = ImageFont.truetype('NotoSansCJK-Black.ttc', 20)
for i in range(0, img_rgba.size[0], len(text) * 20 + 80):
for j in range(0, img_rgba.size[1], 200):
draw.text((i, j), text, font=font, fill=(0, 0, 0, 50))
# 旋转文字 45 度
text_img = text_img.rotate(-45)
# 合成水印图片
img_with_watermark = Image.alpha_composite(img_rgba, text_img)
# 原始图片尺寸
img_with_watermark = img_with_watermark.crop((width, height, width * 2, height * 2))
img_with_watermark.show()
return img_with_watermark.convert("RGB")
if __name__ == '__main__':
img_file = "/path/to/test.jpg"
text = u'AIUAI 测试使用'
img_pil = Image.open(img_file)
#out_img = add_watermark_fun1(img_pil, text)
out_img = add_watermark_fun2(img_pil, text)
out_img.save("/path/to/save/out_img.jpg", 'JPEG', quality=100)
print("[INFO]Done.")
如: