本篇文章为大家展示了Python使用Pillow添加图片水印的方法,代码简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
如果在某个网站上发布了图片,希望在图片上会出现带标识的水印着怎么办呢。
这个是个比较常见的需求,在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
上述内容就是Python使用Pillow添加图片水印的方法,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。