目录
题目:
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。类似于图中效果:
学习内容
虽然python学的不久,但是用Pillow库解决图像方面的问题还是知道的。这个题目的解决思路就是:如何用Pillow库实现在一个图像的某一个像素位置插入一个text字段。
Load an Image
To load an image from a file, use the open()
function in the Image module:
>>> from PIL import Image
>>> im = Image.open("hopper.ppm")
If successful, this function returns an Image object. If the file cannot be opened, an IOError
exception is raised.
ImageFont Module
The ImageFont
module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the PIL.ImageDraw.Draw.text()
method.
font字体在Image模块中被当做bitmap位图处理,也就是一种图片格式。添加字体其实就是在一张图片上添加bitmap格式的font图片。
from PIL import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
ImageDraw Module
Example: Draw Partial Opacity Text
from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('Pillow/Tests/images/hopper.png').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))
# get a font
fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)
# draw text, half opacity
d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.text((10,60), "World", font=fnt, fill=(255,255,255,255))
out = Image.alpha_composite(base, txt)
out.show()
PIL.ImageDraw.ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None)
解决代码
from PIL import Image, ImageFont, ImageDraw
image = Image.open(r'C:\Users\ChanWunsam\Desktop\0.png')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial.ttf', 25)
draw.text((230,10), '10', fill='red', font=font)
# del draw ## 释放ImageDraw.Draw缓存,不过不影响结果,感觉也非必要
image.save(r'C:\Users\ChanWunsam\Desktop\0_1.png', format='PNG')
image.close()
别人的解决方法
我的方法是看文档做出来的,确实没有看过别人的源码。不过看起来思路一样,就是他的在细节方面比我更好。
from PIL import Image, ImageFont, ImageDraw
image = Image.open('0.png')
w, h = image.size
font = ImageFont.truetype('arial.ttf', 50)
draw = ImageDraw.Draw(image)
draw.text((4*w/5, h/5), '5', fill=(255, 10, 10), font=font)
image.save('0.0.png', 'png')