原文:
http://www.cnblogs.com/SeekHit/p/6101867.html
早些年,微信朋友圈有段時間非常流行這個頭像+1的套路,簡直逼死強迫症。
将你的 QQ 頭像(或者微網誌頭像)右上角加上紅色的數字,類似于微信未讀資訊數量那種提示效果。 類似于圖中效果

涉及知識:
Python Imaging Library (PIL)圖像庫,Image, ImageDraw, ImageFont子產品
話不多說先上代碼:
1 from PIL import Image, ImageDraw, ImageFont
2
3 def add_num(img):
4 draw = ImageDraw.Draw(img)
5 myfont = ImageFont.truetype("C:\\WINDOWS\\Fonts\\SIMYOU.TTF", 200)
6 width, height = img.size
7 draw.ellipse((width-200,0,width,200),fill="red",outline ="red")
8 draw.text((width-150, 15), '1', font=myfont, fill="white")
9
10 img.save('result.jpg','jpeg')
11
12 image = Image.open('yoyo.jpg')
13 add_num(image)
其中ImageFont.truetype(file,size) ? Font instance
含義:加載一個TrueType或者OpenType字型檔案,并且建立一個字型對象。這個函數從指定的檔案加載了一個字型對象,并且為指定大小的字型建立了字型對象。
在windows系統中,如果指定的檔案不存在,加載器會順便看看windows的字型目錄下是否存在。
繪制效果:
過程中可能會出現的問題:
首先是PIL庫的安裝。我用的是pycharm,Python版本2.7。第一次裝也是裝了幾次才成功,主要原因是,通過pycharm直接安裝,裡面裝的版本隻有1.1.6的,安裝之後,運作不了,會提示你找不到合适的Python版本。
然後我就去網上查了下,知道了PIL庫主要2.5 2.6用的比較多,2.7需要裝最新版的庫。
The following downloads are currently available:
PIL 1.1.7
- Python Imaging Library 1.1.7 Source Kit (all platforms) (November 15, 2009)
- Python Imaging Library 1.1.7 for Python 2.4 (Windows only)
- Python Imaging Library 1.1.7 for Python 2.5 (Windows only)
- Python Imaging Library 1.1.7 for Python 2.6 (Windows only)
- Python Imaging Library 1.1.7 for Python 2.7 (Windows only)
Additional downloads may be found here.
PIL 1.1.6
- Python Imaging Library 1.1.6 Source Kit (all platforms) (440k TAR GZ) (December 3, 2006)
- Python Imaging Library 1.1.6 for Python 2.2 (Windows only)
- Python Imaging Library 1.1.6 for Python 2.3 (Windows only)
- Python Imaging Library 1.1.6 for Python 2.4 (Windows only)
- Python Imaging Library 1.1.6 for Python 2.5 (Windows only)
- Python Imaging Library 1.1.6 for Python 2.6 (Windows only)
然後下載下傳了2.7可以用的1.1.7,輕按兩下安裝,然後再Pycharm - File - Setting - Project Interpreter - Available Packages 然後面闆左下角的Manage Repositories中添加,PIL安裝的路徑,我的路徑是(C:\Python27\Lib\site-packages\PIL)。
退回到settings界面,可以看到PIL庫已經安裝好了。
【個人追記】
上述的PIL安裝包适用于win32系統,win64請自行搜尋下載下傳
》ImageDraw.Draw(img)
建立一個圖形處理對象,參數為打開之後的圖形
》ImageFont.truetype("C:\\WINDOWS\\Fonts\\SIMYOU.TTF", 200)
定義了文字的樣式和大小,第一個參數為樣式,第二個參數為大小
》draw.ellipse((width-200,0,width,200),fill="red",outline ="red")
在draw圖形對象上畫一個圓/橢圓,将這個圓/橢圓看成裝在一個矩形裡面,
前四個參數分别代表圓/橢圓的x,y坐标(X1,Y1),右下角的x,y坐标(X2,Y2)
當這個矩形是正方形時,畫出來的是圓,否則是橢圓。
fill = 這個圓/橢圓 内部被填充成了什麼顔色,outline = 這個圓/橢圓的邊界線是什麼顔色
》draw.text((width-150, 15),'1', font=myfont, fill="white")
在draw圖形對象上添加一個文字框,坐标是(width-150, 15),内容是1,
用front的樣式,字型填充色是white。
imageDraw,imageFornt參考:
http://blog.csdn.net/dou_co/article/details/17618319
http://www.aichengxu.com/python/39904.htm
以上。