|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | + |
| 4 | +@description: |
| 5 | +""" |
| 6 | + |
| 7 | +from PIL import Image, ImageDraw |
| 8 | + |
| 9 | + |
| 10 | +# 指定要使用的字体和大小;黑体,24号 |
| 11 | +# font = ImageFont.truetype('heiti.ttf', 24) |
| 12 | + |
| 13 | + |
| 14 | +# image: 图片 text:要添加的文本 font:字体 |
| 15 | +def add_text_watermark(image_path, text, font=None): |
| 16 | + image = Image.open(image_path) |
| 17 | + rgba_image = image.convert('RGBA') |
| 18 | + text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0)) |
| 19 | + # (255,255,255,0):第四个是图片的透明度,值越大,越浅 |
| 20 | + image_draw = ImageDraw.Draw(text_overlay) |
| 21 | + print(rgba_image) |
| 22 | + # 设置文本文字位置 |
| 23 | + text_xy = (rgba_image.size[0] - 80, rgba_image.size[1] - 80) |
| 24 | + # 设置文本颜色和透明度 |
| 25 | + image_draw.text(text_xy, text, fill=(87, 250, 255, 360), font=None) |
| 26 | + # (87,250,255,360)第四个是文字的透明度,值越大,越深 |
| 27 | + out = Image.alpha_composite(rgba_image, text_overlay) |
| 28 | + |
| 29 | + return out |
| 30 | + |
| 31 | + |
| 32 | +def add_logo_watermark(src_path, mask_path, rate=0.1): |
| 33 | + im = Image.open(src_path) |
| 34 | + mask = Image.open(mask_path) |
| 35 | + |
| 36 | + h, w = im.size[0], im.size[1] |
| 37 | + if w > h: |
| 38 | + limit = int(w * rate) |
| 39 | + else: |
| 40 | + limit = int(h * rate) |
| 41 | + mask = mask.resize((limit, int(limit * mask.size[1] / mask.size[0]))) |
| 42 | + |
| 43 | + layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) |
| 44 | + layer.paste(mask, (im.size[0] - 80, im.size[1] - 60)) |
| 45 | + out = Image.composite(layer, im, layer) |
| 46 | + |
| 47 | + return out |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + image_path = './search/data/images/car-1.jpg' |
| 52 | + mask_path = './search/data/images/car-2.jpg' |
| 53 | + im_after = add_text_watermark(image_path, 'world') |
| 54 | + im_after.show() |
| 55 | + im_after_logo = add_logo_watermark(image_path, mask_path) |
| 56 | + im_after_logo.show() |
0 commit comments