Python 练习册 0-头像右上角添加数字

Python 练习册,每天一个小程序,原题来自Yixiaohan/show-me-the-code
我的代码仓库在Github

目标

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

类似于图中效果:

《Python 练习册 0-头像右上角添加数字》

《Python 练习册 0-头像右上角添加数字》

安装PIL

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

在命令行中通过pip安装

$ pip install pillow

解决方案

该题目的代码实现如下:

# 引入Pillow
from PIL import Image, ImageDraw, ImageFont, ImageColor
def add_num(img):
    # 创建一个Draw对象
    draw = ImageDraw.Draw(img)
    # 创建一个 Font
    myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=40)
    fillcolor = ImageColor.colormap.get('red')
    width, height = img.size
    draw.text((width-30, 0), '1', font=myfont, fill=fillcolor)
    img.save('result.jpg', 'jpeg')
    return 0
if __name__ == '__main__':
    image = Image.open('test.jpg')
    add_num(image)

如果想要详细了解Pillow的使用,请参考Pillow 官方文档

    原文作者:王鹏程Orange
    原文地址: https://www.jianshu.com/p/05e3973a77ed
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞