python练习

来源:互联网 发布:期货软件大赢家 编辑:程序博客网 时间:2024/06/05 03:36

第0000题:将你的QQ头像(或是微博头像)右上角加上红色的数字,类似微信未读信息数量那种提示效果。类似图中效果


分析:这题采用了最常用的图像处理库 PIL


首先介绍PIL模块中的画图函数:

1.Image.open(image)

加载图片

2.ImageDraw.Draw(image)

 创建一个绘图对象,即背景

3.drawObject.text(position,  string,  options)

在图像内添加文字

Position:一个二元元组,指定字符串左上角坐标

string:写入的字符串

options选项可以为fill或者font,其中fill指定字的颜色,font指定字体与字的尺寸,font必须为ImageFont中指定的font类型

4.ImageFont.truetype(filename ,   wordsize) 

创建字体对象

filenane:字体文件的名称,通常为ttf文件,还有少数ttc文件,可以在C:\Windows\Fonts中找到

wordsize:字体大小

5.image.show()

显示图片

代码如下

from PIL import Image,ImageDraw,ImageFontdef add_num(picPath,num):img=Image.open(picPath) #加载图片x,y=img.size#获取图片大小myfont=ImageFont.truetype("simsun.ttc",x/3) #truetype(filename ,   wordsize) 创建字体对象ImageDraw.Draw(img).text((2*x/3,0),str(num),font=myfont,fill='red')#ImageDraw.Draw创建绘图对象#text(position,  string,  options) 添加文字img.save('pic_with_num.jpg')img.show()if __name__=='__main__':add_num('images.jpg',5)</span></span>

效果图如下:



参考

[1].https://github.com/Show-Me-the-Code/show-me-the-code.git

[2].https://www.anotherhome.net/1917


0 0