文章目录
前言
一、PIL是什么?
二、安装PIL
pip install pillow
三、查看PIL版本
pip show pillow
四、使用PIL库给图片添加文本水印
1.引入库
from PIL import Image, ImageDraw, ImageFont
2.打开图片文件
local = '/Users/kkstar/Downloads/video/pic/'
image = Image.open(local+"demo.jpg")
3.新建一个Draw对象
draw = ImageDraw.Draw(image)
4.设置水印文字、字体、大小
text = '@空空star'
font = ImageFont.truetype('STHeitiMedium.ttc', size=80)
5.设置水印颜色
5.1通过名称设置颜色
# 通过名称设置颜色-黄色
color = 'yellow'

5.2通过RGB值设置颜色
# 通过RGB值设置颜色-红色
color = (255, 0, 0)

5.3通过RGBA值设置颜色
# 通过RGBA值设置颜色-白色
color = (255,255,255,0)

5.4通过十六进制设置颜色
# 通过十六进制设置颜色-绿色
color = '#6FE000'

6.获取水印文字的尺寸
text_width, text_height = draw.textsize(text, font)
7.设置水印位置
7.1左上
x = 30
y = 30

7.2右下
x = image.width-text_width-30
y = image.height-text_height-30

8.添加水印
draw.text((x, y), text, font=font, fill=color)
9.保存图片
image.save(local+'image_with_watermark.jpg')