Pillow 文字水印背景
时间: 2023-08-19 07:04:51 浏览: 47
你可以使用 Pillow 库中的 ImageDraw 模块来添加文字水印,并通过 ImageOps 模块中的 colorize() 方法来添加背景色。
以下是一个示例代码:
```python
from PIL import Image, ImageDraw, ImageOps, ImageFont
# 打开图片
image = Image.open('image.jpg')
# 创建 ImageDraw 对象
draw = ImageDraw.Draw(image)
# 设置字体和文字
font = ImageFont.truetype('arial.ttf', 36)
text = 'watermark'
# 获取文字大小
text_width, text_height = draw.textsize(text, font)
# 设置文字位置
x = image.width - text_width - 20
y = image.height - text_height - 20
# 添加背景色
background = ImageOps.colorize(Image.new('RGBA', (text_width, text_height), (0, 0, 0, 128)), (255, 255, 255))
# 合并背景色和文字
background.paste(ImageOps.colorize(Image.new('RGBA', (text_width, text_height), (255, 255, 255, 0)), (255, 255, 255)), (0, 0), ImageOps.invert(background))
background.paste(ImageOps.colorize(Image.new('RGBA', (text_width, text_height), (255, 255, 255, 0)), (0, 0, 0)), (0, 0), background)
# 添加文字水印
draw.text((x, y), text, font=font, fill=(255, 255, 255))
# 保存图片
image.save('watermarked_image.jpg')
```
这个示例代码会在图片的右下角添加一个带有背景色的文字水印。你可以调整背景色和文字位置等参数,以满足你的需求。