Python使用Pillow添加图片水印

2025-12-02 0 56,800

如果在某个网站上发布了图片,希望在图片上会出现带标识的水印着怎么办呢。

这个是个比较常见的需求,在Python中应该如何处理这一类需求呢?

需要先安装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, 'py.com', 'red')
    with open('new_image_water.png', 'wb') as f:
        image_with_watermark.save(f)

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

这个只是把文本嵌入到图片中的实现,其实也可以嵌入一个图片进去的。具体可以参考pillow官方文档:

https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.alpha_composite

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python高级 Python使用Pillow添加图片水印 https://www.zhiup.top/6285.html

相关