Python 给图标添加水印,防止被盗用
1 import os 2 from PIL import Image, ImageDraw, ImageFont 3 4 5 def add_text_to_image(image, text): 6 font = ImageFont.truetype('C:\Windows\Fonts\AdobeHeitiStd-Regular.otf', 50) # 字体 50大小 7 8 # 添加背景 9 new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0)) 10 new_img.paste(image, image.size) 11 12 # 添加水印 13 font_len = len(text) 14 rgba_image = new_img.convert('RGBA') 15 text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0)) 16 image_draw = ImageDraw.Draw(text_overlay) 17 18 for i in range(0, rgba_image.size[0], font_len * 40 + 100): 19 for j in range(0, rgba_image.size[1], 200): 20 image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 50)) 21 text_overlay = text_overlay.rotate(-45) 22 image_with_text = Image.alpha_composite(rgba_image, text_overlay) 23 24 # 裁切图片 25 image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2)) 26 return image_with_text 27 28 29 if __name__ == '__main__': 30 print(os.listdir('./img')) 31 for img in os.listdir('./img'): 32 print("./img/"+img) 33 Img = Image.open("./img/"+img) 34 im_after = add_text_to_image(Img, u'沃马外卖 盗用非法 仅供展示') 35 im_after.save(u'./out_img/' + str(img)[0:-4] + '.png') 36 print('完')
效果图