第 0000 題: 將你的 QQ 頭像(或者微博頭像)右上角加上紅色的數(shù)字贬丛,類似于微信未讀信息數(shù)量那種提示效果硼补。 類似于圖中效果
Python練習(xí)冊(cè),每天一個(gè)小程序:https://github.com/Yixiaohan/show-me-the-code
前提:
PIL:Python Imaging Library
由于PIL僅支持到Python 2.7授舟,加上年久失修,于是一群志愿者在PIL的基礎(chǔ)上創(chuàng)建了兼容的版本昭雌,名字叫Pillow渔扎,支持最新Python 3.x
聲明:
代碼copy自漢森x, 自己只是加了大量注釋. 侵刪.
from PIL import Image, ImageFont, ImageDraw
def white_to_transparent(img):
"""摳圖"""
#convert()函數(shù)志鹃,用于不同模式圖像之間的轉(zhuǎn)換夭问。
#PIL中有九種不同模式,分別為1曹铃,L缰趋,P,RGB陕见,RGBA秘血,CMYK,YCbCr评甜,I灰粮,F(xiàn)。
#模式“1”為二值圖像忍坷,非黑即白粘舟。模式“L”為灰色圖像.模式“P”為8位彩色圖像.模式“RGBA”為32位彩色圖像.
#模式“I”為32位整型灰色圖像.模式“F”為32位浮點(diǎn)灰色圖像.
img = img.convert('RGBA') #返回一個(gè)轉(zhuǎn)換后的圖像副本
datas = img.getdata() #像素?cái)?shù)據(jù)隊(duì)列
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255:
newData.append((255,255,255,0)) #把白色變?yōu)橥该魃? else:
newData.append(item)
img.putdata(newData) #賦值給圖片新的像素?cái)?shù)據(jù)
img.save("change.png","PNG")
return img
if __name__ == "__main__":
p1_name = "github_logo" #the path of image.
p2_name = "red_reminder"
p1_image = Image.open(p1_name) #make a Image object
p2_image = Image.open(p2_name)
p2_transparent=white_to_transparent(p2_image)
p1_image.paste(p2_transparent,(0,0),p2_transparent) #paste方法?
#usr_font=ImageFont.truetype("usr/share/fonts/truetype\
# /deepin/DeepinOpenSymbol.ttf",32)
usr_font = ImageFont.truetype("./FZZCHJW.TTF",32)
#If"can't open resource" it means, python can't find your font.
#Use absolute path, rather than relative path.
draw=ImageDraw.Draw(p1_image) #在p1_image上繪制文字,圖像
draw.text((152,8),u'10',font=usr_font)
p1_image.save("final.png","PNG")
final.png
red_reminder
github_logo
以及一個(gè)字體文件, 可以選用系統(tǒng)自帶的字體.