文章目录
- 前言
- 一、PIL是什么?
- 二、安装PIL
- 三、查看PIL版本
- 四、使用PIL库给图片添加文本水印
- 1.引入库
- 2.打开图片文件
- 3.新建一个Draw对象
- 4.设置水印文字、字体、大小
- 5.设置水印颜色
- 5.1通过名称设置颜色
- 5.2通过RGB值设置颜色
- 5.3通过RGBA值设置颜色
- 5.4通过十六进制设置颜色
- 6.获取水印文字的尺寸
- 7.设置水印位置
- 7.1左上
- 7.2右下
- 8.添加水印
- 9.保存图片
- 总结
前言
大家好,我是空空star,本篇给大家分享一下通过Python的PIL库给图片添加文本水印。
一、PIL是什么?
PIL是Python Imaging Library的缩写,它是Python语言中常用的图像处理库之一。它提供了丰富的图像处理功能,包括打开、保存、裁剪、旋转、缩放等操作,并支持多种图像格式。
二、安装PIL
python">pip install pillow
三、查看PIL版本
python">pip show pillow
Name: Pillow
Version: 9.4.0
Summary: Python Imaging Library (Fork)
Home-page: https://python-pillow.org
Author: Alex Clark (PIL Fork Author)
Author-email: aclark@python-pillow.org
License: HPND
Requires:
Required-by: image, imageio, matplotlib, pytesseract, wordcloud
四、使用PIL库给图片添加文本水印
1.引入库
python">from PIL import Image, ImageDraw, ImageFont
2.打开图片文件
python">local = '/Users/kkstar/Downloads/video/pic/'
image = Image.open(local+"demo.jpg")
3.新建一个Draw对象
python">draw = ImageDraw.Draw(image)
4.设置水印文字、字体、大小
python">text = '@空空star'
font = ImageFont.truetype('STHeitiMedium.ttc', size=80)
5.设置水印颜色
5.1通过名称设置颜色
python"># 通过名称设置颜色-黄色
color = 'yellow'
![](https://img-blog.csdnimg.cn/89f0b06efa044ac48156daa665d0de5f.jpeg)
5.2通过RGB值设置颜色
python"># 通过RGB值设置颜色-红色
color = (255, 0, 0)
![](https://img-blog.csdnimg.cn/9d33363b0b21475d974231b9e1dff2e2.jpeg)
5.3通过RGBA值设置颜色
python"># 通过RGBA值设置颜色-白色
color = (255,255,255,0)
![](https://img-blog.csdnimg.cn/1054f50d2e0b442cb6e744e444f57d8c.jpeg)
5.4通过十六进制设置颜色
python"># 通过十六进制设置颜色-绿色
color = '#6FE000'
![](https://img-blog.csdnimg.cn/3f1ec495533f4e93a531c84168afd463.jpeg)
6.获取水印文字的尺寸
python">text_width, text_height = draw.textsize(text, font)
7.设置水印位置
7.1左上
python">x = 30
y = 30
![](https://img-blog.csdnimg.cn/89f0b06efa044ac48156daa665d0de5f.jpeg)
7.2右下
python">x = image.width-text_width-30
y = image.height-text_height-30
![](https://img-blog.csdnimg.cn/0fb55bcab7824e7289be0467259c46d7.jpeg)
其他位置调整x、y的值即可。这个30是我这样设置的,你也可以根据自己的喜好来调整。
8.添加水印
python">draw.text((x, y), text, font=font, fill=color)
9.保存图片
python">image.save(local+'image_with_watermark.jpg')