题目:在头像(QQ、微信等)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。
下面是示例,在图片上加数字。
用PS很简单就可以做到,但是如何用Python完成呢?
一、思路:利用Python强大的图片处理库——Pillow
下面介绍今天会用到的模块:The ImageDraw Module,他的功能如下,
支持2D图像
创建绘画对象
基本绘画操作弧/弦/扇形 chord arc pieslice (bbox, strtAng, endAng)
椭圆 ellipse (bbox)
线段/多段线 line (L) draw.line(((60,60),(90,60), (90,90), (60,90), (60,60))) #draw a square
点 point (xy) #单像素点很小看不清,实际中可用实心小圆代替
多边形 polygon (L) draw.polygon([(60,60), (90,60), (90,90), (60,90)]) #draw a square
矩形 rectangle (bbox) # first coord属于矩形, second coord不属于
文字 text(xy,message,font=None) 绘制文字message,文本区域左上角坐标为xy
drawable.text((10, 10), "Hello", fill=(255,0,0), font=None)
文字大小 textsize(message,font=None) 给定文字message,返回所占像素(width,height)
可选参数
矢量字体支持
二、示例练习
环境:Python3.5
from PIL import Image, ImageDraw, ImageFont
img = Image.open('girl.jpg')
draw = ImageDraw.Draw(img)
myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=80)
fillcolor = "#ff0000"
width, height = img.size
draw.text((40,40),'hello', font=myfont, fill=fillcolor)
img.save('result.jpg','jpeg')
效果展示:
也就是在原图上加入文字,下面一步步分析过程。
from PIL import Image, ImageDraw, ImageFont
首先导入相关模块,没有安装可以直接用pip安装
img = Image.open('girl.jpg')
draw = ImageDraw.Draw(img)
打开图片girl.jpg
myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=80)
fillcolor = "#ff0000"
width, height = img.size
Arial.ttf是电脑上安装的字体,fillcolor是填充颜色,#ff0000是十六进制颜色
draw.text((40,40),'hello', font=myfont, fill=fillcolor)
img.save('result.jpg','jpeg')
最后就是添加文字了,(40,40)是位置,'hello'自定义,最后保存。
三、总结
好了,今天的题目讲完了,其中我也遇到很多困难,我准备在图片中加入中文,但是文字无法正常显示,朋友们,有谁知道答案吗?
打算以后每天写一篇题目解析,这些题目在github上都有,最后求一波star(๑• . •๑)
这是@史江歌大神整理的Python题目,我会详细讲解过程Yixiaohan/show-me-the-code
最后,我想给自己定个目标,2017年利用Python找到一份工作,养活自己。
你呢?