Python 中使用 Pillow 处理图片增加水印,保护你的图片版权

85 阅读1分钟

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理

以下文章来源于腾讯云 作者:the5fire

( 想要学习Python?Python学习交流群:1039649593,满足你的需求,资料都已经上传群文件流,可以自行下载!还有海量最新2020python学习资料。 ) 在这里插入图片描述 这个是个比较常见的需求,比如你在某个网站上发布了图片,在图片上就会出现带你昵称的水印。那么在Python中应该如何处理这一类需求呢?

其实在我的《Django实战开发》视频教程中有讲到这一部分,Django结合了xadmin,再集成进来 django-ckeditor之后,有了比较方便的富文本编辑器了,对于图片也就需要增加一个水印的功能。这里把其中的代码抽一部分出来,仅供参考。

需要先安装

Pillow: pip install pillow

Demo代码:

import sys

from PIL import Image, ImageDraw, ImageFont


def watermark_with_text(file_obj, text, color, fontfamily=None):
    image = Image.open(file_obj).convert('RGBA')
    draw = ImageDraw.Draw(image)
    width, height = image.size
    margin = 10
    if fontfamily:
        font = ImageFont.truetype(fontfamily, int(height / 20))
    else:
        font = None
    textWidth, textHeight = draw.textsize(text, font)
    x = (width - textWidth - margin) / 2  # 计算横轴位置
    y = height - textHeight - margin  # 计算纵轴位置
    draw.text((x, y), text, color, font)

    return image


if __name__ == '__main__':
    org_file = sys.argv[1]
    with open(org_file, 'rb') as f:
        image_with_watermark = watermark_with_text(f, 'the5fire.com', 'red')

    with open('new_image_water.png', 'wb') as f:
        image_with_watermark.save(f)

使用方法: python watermart.py <图片地址>