说明
这个是网上一些大佬做的一套练习题,总共有25题,训练大家python在文件读取、文本处理、数据库、网页等方向的熟练度,十分有用。github地址在这:
上不了github的可以直接搜名字,应该能搜到。
我这个笔记集也是只记了五道题。。。我大概多做了一两题吧,唉。。。。。。
题目:
将你的 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, ImageDrawdraw = ImageDraw.Draw(image)# use a bitmap fontfont = ImageFont.load("arial.pil")draw.text((10, 10), "hello", font=font)# use a truetype fontfont = 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 imagebase = Image.open('Pillow/Tests/images/hopper.png').convert('RGBA')# make a blank image for the text, initialized to transparent text colortxt = Image.new('RGBA', base.size, (255,255,255,0))# get a fontfnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)# get a drawing contextd = ImageDraw.Draw(txt)# draw text, half opacityd.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))# draw text, full opacityd.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, ImageDrawimage = 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, ImageDrawimage = Image.open('0.png')w, h = image.sizefont = 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')