Python练习册--PIL处理图片之加水印

背景

最近在看到了Python 练习册,每天一个小程序 这个项目,非常有趣,也比较实用.

晚上看了这第000题,关于Python图片处理:

将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果

之前没怎么使用过PIL库,在生成验证码及识别验证码时也需要了解这方面知识,就动手试了实践下.


PIL

The Python Imaging Library adds image processing capabilities to your Python interpreter. 这个库提供了广泛的文件格式支持、高效的内部表示以及相当强大的图像处理功能。

文档在这:http://omz-software.com/pythonista/docs/ios/PIL.html

思路

题目的意思实际就是为图片加水印,具体可分以下2步:

  1. 将文本"转"成图片
  2. 将生成的水印图片跟原图相"叠加"

原理差不多就是这样子,具体处理还得使用PIL.


image alt text

最后贴上代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2014-11-29 19:09:59 # @Author : Linsir (vi5i0n@hotmail.com) # @Link : http://Linsir.sinaapp.com import Image, ImageEnhance, ImageDraw, ImageFont def text2img(text, font_color="Blue", font_size=25): """生成内容为 TEXT 的水印""" font = ImageFont.truetype('simsun.ttc', font_size) #多行文字处理 text = text.split('\n') mark_width = 0 for i in range(len(text)): (width, height) = font.getsize(text[i]) if mark_width < width: mark_width = width mark_height = height * len(text) #生成水印图片 mark = Image.new('RGBA', (mark_width,mark_height)) draw = ImageDraw.ImageDraw(mark, "RGBA") draw.setfont(font) for i in range(len(text)): (width, height) = font.getsize(text[i]) draw.text((0, i*height), text[i], fill=font_color) return mark def set_opacity(im, opacity): """设置透明度""" assert opacity >=0 and opacity < 1 if im.mode != "RGBA": im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = 

转载于:https://www.cnblogs.com/apexchu/p/4231032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值