python 练习0000
要求
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。
代码实现
from PIL import Image, ImageFont, ImageDraw, ImageColor
def add_circle(image):
width, height = image.size
draw = ImageDraw.Draw(image)
# 圆的半径、横纵坐标
r = 50
x = width - r
y = 50
# 画圆的位置 右上角
position = (x - r, y - r, x + r, y + r)
# 颜色
color = ImageColor.colormap.get('red')
# 画圆
draw.ellipse(position, fill=color)
return image
def add_num(image, num):
if int(num) > 99:
num = '99+'
# 获取图片的大小
width, height = image.size
# 设置字体
font = ImageFont.truetype('arial.ttf', 50)
# 设置字体颜色
font_color = ImageColor.colormap.get('white')
# 将字体加到图片上
draw = ImageDraw.Draw(image)
# 位置
position = [(0, 0), (width - 65, 22), (width - 80, 22), (width - 90,22)]
position = position[len(num)]
draw.text(position, num, font=font, fill=font_color)
return image
def generate(image_path, num):
image = Image.open(image_path)
# 现在原图像右上角画一个红色圆
image = add_circle(image)
# 在右上角写数字
image = add_num(image, num)
# 保存
path = '.\\\\pic\\\\result.jpg'
image.save(path)
if __name__ == '__main__':
image_path = '.\\\\pic\\\\head.jpg'
num = '100'
generate(image_path, num)