• 技术文章 >Python技术 >Python高级

    Python使用Pillow添加图片水印

    PythonPython2019-06-03 15:04:31原创5073
    如果在某个网站上发布了图片,希望在图片上会出现带标识的水印着怎么办呢。

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

    需要先安装Pillow: pip install pillow

    Demo代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    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

    专题推荐:python
    上一篇:Elasticsearch基本介绍及其与Python的对接实现 下一篇:深究Python中的asyncio库-线程并发函数

    相关文章推荐

    • 2019 Python 计算生态五月推荐榜

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网