-
-
Save cash2one/f824847c02e84563dd3045dc8077337c to your computer and use it in GitHub Desktop.
python watermark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from PIL import Image, ImageEnhance, ImageDraw, ImageFont | |
| def text2img(text, font_color="Black", font_size=30): | |
| """生成内容为 TEXT 的水印""" | |
| font = ImageFont.truetype('/Users/liuzenglu/Documents/yahei.ttf', font_size) | |
| # 多行文字处理 | |
| text = text.split('\n') | |
| mark_width = 0 | |
| for i in range(len(text)): | |
| (width, height) = font.getsize(text[i]) | |
| if mark_width < width: | |
| mark_width = width | |
| mark_height = height * len(text) | |
| # 生成水印图片 | |
| mark = Image.new('RGBA', (mark_width, mark_height)) | |
| draw = ImageDraw.ImageDraw(mark, "RGBA") | |
| draw.font = font | |
| for i in range(len(text)): | |
| (width, height) = font.getsize(text[i]) | |
| draw.text((0, i*height), text[i], fill=font_color) | |
| return mark | |
| def set_opacity(im, opacity): | |
| """设置透明度""" | |
| assert opacity >= 0 and opacity < 1 | |
| if im.mode != "RGBA": | |
| im = im.convert('RGBA') | |
| else: | |
| im = im.copy() | |
| alpha = im.split()[3] | |
| alpha = ImageEnhance.Brightness(alpha).enhance(opacity) | |
| im.putalpha(alpha) | |
| return im | |
| def watermark(im, mark, position, opacity=1, margin=5): | |
| """添加水印""" | |
| if opacity < 1: | |
| mark = set_opacity(mark, opacity) | |
| if im.mode != 'RGBA': | |
| im = im.convert('RGBA') | |
| if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]: | |
| raise("The mark image size is larger size than original image file.") | |
| # 设置水印位置 | |
| if position == 'left_top': | |
| x = margin | |
| y = margin | |
| elif position == 'left_bottom': | |
| x = margin | |
| y = im.size[1] - mark.size[1] | |
| elif position == 'right_top': | |
| x = im.size[0] - mark.size[0] | |
| y = margin | |
| elif position == 'right_bottom': | |
| x = im.size[0] - mark.size[0] | |
| y = im.size[1] - mark.size[1] | |
| else: | |
| x = (im.size[0] - mark.size[0]) / 2 | |
| y = (im.size[1] - mark.size[1]) / 2 | |
| x, y = int(x), int(y) | |
| layer = Image.new('RGBA', im.size,) | |
| layer.paste(mark, (x, y)) | |
| return Image.composite(layer, im, layer) | |
| if __name__ == '__main__': | |
| text = '仅供比特币中国使用' | |
| fn = '/Users/liuzenglu/Desktop/WechatIMG11.jpeg' | |
| im = Image.open(fn) | |
| mark = text2img(text) | |
| image = watermark(im, mark, 'left_top') | |
| out_file = '/%s/%s-o.png' % (os.path.join(*fn.split('/')[:-1]), fn.split('/')[-1].split('.')[0]) | |
| image.save(out_file) | |
| image.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment