通过Python的PIL库给图片添加文本水印


前言

大家好,我是空空star,本篇给大家分享一下通过Python的PIL库给图片添加文本水印。


一、PIL是什么?

PIL是Python Imaging Library的缩写,它是Python语言中常用的图像处理库之一。它提供了丰富的图像处理功能,包括打开、保存、裁剪、旋转、缩放等操作,并支持多种图像格式。

二、安装PIL

pip install pillow

三、查看PIL版本

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: [email protected]
License: HPND
Requires:
Required-by: image, imageio, matplotlib, pytesseract, wordcloud

四、使用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

其他位置调整x、y的值即可。这个30是我这样设置的,你也可以根据自己的喜好来调整。

8.添加水印

draw.text((x, y), text, font=font, fill=color)

9.保存图片

image.save(local+'image_with_watermark.jpg')

总结

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>