from PIL import Image, ImageDraw, ImageFont
def add_water(image, text, fontsize):
# 字体文件
font = ImageFont.truetype('1641789485961483.otf', fontsize)
# 添加背景
new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (255, 255, 255, 255))
new_img.paste(image, image.size)
# 添加水印
font_len = len(text)
rgba_image = new_img.convert('RGBA')
text_overlay = Image.new('RGBA', rgba_image.size, (0, 0, 0, 0))
image_draw = ImageDraw.Draw(text_overlay)
# 水印数量
for i in range(0, rgba_image.size[0], font_len * 40 + 300):
for j in range(0, rgba_image.size[1], 300):
# print(f'i:{i}, j:{j}, text:{text}, font:{font}')
image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 50))
# 水印文字角度
text_overlay = text_overlay.rotate(45)
image_with_text = Image.alpha_composite(rgba_image, text_overlay)
image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
return image_with_text
if __name__ == '__main__':
pic = '1.png' # 需要加水印的图片
text = "我是水印" # 水印文字
fontsize = 32 # 文字大小
img = Image.open(pic)
fill_img = add_water(img, text, fontsize)
# 一定要保存为png格式
fill_img.save(u'2.png')