在知乎上看到的推荐,感觉还有点意思,遂记录之,这是开篇。

题目地址:点这里

题目描述

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

PIL

PIL:Python Imaging Library,Python平台上的图像处理库。PIL功能强大,而且API简单易用。但是PIL仅支持到Python 2.7,有人在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。

下面给出pillow的官方文档

ImageDraw

首先,研究一下官方文档:
The ImageDraw module provides simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.

Example:Draw a gray cross over an image

1
2
3
4
5
6
7
8
9
10
11
from PIL import Image, ImageDraw

im = Image.open("hopper.jpg")

draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
del draw

# write to stdout
im.save(sys.stdout, "PNG")

大致分为以下几个步骤:

1.打开图片
2.创建对象
3.绘制
4.输出

绘制

这是最核心的部分,我们进行详细的讨论,题目给的要求是:右上角加上红色的数字。

这里有两个关键点:

1.右上角
2.红色

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#  _*_ coding:utf-8 _*_
__author__ = 'daqing'
__date__ = '2017/8/7 19:30'

from PIL import Image,ImageDraw,ImageFont

def addNum(nub,filepath):
img = Image.open(filepath)

# 新建draw对象
draw = ImageDraw.Draw(img)
width,height = img.size
fontSize = height/4
#字体
myFont = ImageFont.truetype('arial.ttf',fontSize)
#位置,数字,颜色,字体
draw.text((width-fontSize,0),nub,(256,0,0),font=myFont)
del draw

img.save('res.png')

if __name__ == '__main__':
addNum('10','test.png')

效果

头像:

头像

添加数字后:

处理后的头像