Python practice small project (1) - add numbers to the picture

When a language has been learned to a certain level, we need to continue to do projects to strengthen its understanding and application. There is an interesting collection of practice projects on github: show-me-the-code . What I'm going to write today is the 0000th question. Let's take a look at its requirements:

Add a red number to the upper right corner of your QQ avatar (or Weibo avatar), similar to the prompt effect of the number of unread messages on WeChat. Similar to the effect in the picture:

demo

Here we use some modules under the PIL library mentioned in yesterday's blog :

from PIL import Image, ImageDraw, ImageFont

The ImageDraw module can be used to create new images, annotate or modify existing images, etc. For more details, please see: ImageDraw .

Next, define a function add_num(img)to operate on the image:

def add_num(img):

    # ImageDraw.Draw()函数会创建一个用来对image进行操作的对象,
    # 对所有即将使用ImageDraw中操作的图片都要先进行这个对象的创建。
    draw = ImageDraw.Draw(img)

    # 设置字体和字号
    myfont = ImageFont.truetype('C:/windows/fonts/ARLRDBD.TTF', size=60)

    # 设置要添加的数字的颜色为红色
    fillcolor = "#ff0000"

    # 昨天博客中提到过的获取图片的属性
    width, height = img.size

    #设置添加数字的位置,具体参数可以自己设置
    draw.text((width/1.2, 20), '99', font=myfont, fill=fillcolor)

    # 将修改后的图片以JPEG格式存储
    img.save('result.jpg','jpeg')

    return 0

The code effect is as follows:

Compare

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645531&siteId=291194637