第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,ImageFont
def 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