Python 给图片添加水印

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from PIL import Image, ImageDraw, ImageFont
import time


def add_text_to_image(image, text):
/
    font = ImageFont.truetype("/Library/Fonts/Songti.ttc", 36)
    # 添加背景
    new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
    new_img.paste(image, image.size)

    # 添加水印
    font_len = len(text)
    rgba_image = new_img.convert('RGBA')
    text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
    image_draw = ImageDraw.Draw(text_overlay)

    i_length = rgba_image.size[0]
    j_length = rgba_image.size[1]
    for i in range(0, i_length, font_len * 40 + 100):
        for j in range(0, j_length, 200):
            image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 100))
    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))
    image_with_text.save(time.strftime('%Y%m%d%H%M%S.png'))


if __name__ == '__main__':
    image = Image.open('test.jpg')
    add_text_to_image(image, u'仅供xxxx使用,他用无效')

你可能感兴趣的:(Python 给图片添加水印)