1. 程式人生 > >隨機生成驗證碼之採坑

隨機生成驗證碼之採坑

考試啦,最後一道題是:

結合PIL庫,製作一個能生成4位隨機數驗證碼圖片的函式。

於是第一次用PIL庫的我就到處百度。

import random
import string
import sys
import math
from PIL import Image,ImageDraw,ImageFont,ImageFilter

# 生成幾位數的驗證碼
number = 4
#生成驗證碼圖片的高度和寬度
size = (129,53)
#背景顏色,預設為白色
bgcolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
#字型顏色,預設為藍色
fontcolor = (0,0,0)
#干擾線顏色。預設為紅色
linecolor = (255,0,0)
#加入干擾線條數的上下限
line_number = (1,5)

#隨機生成一個字串
source = ['0','1','2','3','4','5','6','7','8','9','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I','J', 'K','L', 'M', 'N','O','P','Q','R','S', 'T', 'U', 'V', 'W', 'Z','X', 'Y']
gene_text = ''.join(random.sample(source,number))#number是生成驗證碼的位數

#繪製干擾線
width,height = size
begin = (0, random.randint(0, height))
end = (74, random.randint(0, height))
image = Image.new('RGBA',(width,height),bgcolor) #建立圖片
draw = ImageDraw.Draw(image)  #建立畫筆
gene_line = draw.line([begin, end], fill = linecolor,width=3)

#生成驗證碼
width,height = size #寬和高
# font = ImageFont.load_default().font #驗證碼預設系統字型
font = ImageFont.truetype("C:/Windows/Fonts/micross.ttf", 40)  #這個load字型的方法我debug了好久
text = gene_text
font_width, font_height = font.getsize(text)
draw.text(((width - font_width) / number, (height - font_height) / number),text,font= font,fill=fontcolor) #填充字串
image = image.transform((width+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #建立扭曲
image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #濾鏡,邊界加強
image.save('idencode.png') #儲存驗證碼圖片
image.show()

輸出結果:

總結一下用到的幾個函式方法:

1、Image.new(mode, size, color=0) 建立一個指定格式、大小的畫布,mode為建立圖片的格式,size有兩個引數(width, height),color預設為黑。

2、ImageDraw.Draw(im, mode=None)建立畫筆在畫布上,在畫布上進行2d繪畫,畫布需為rgb或者rgba格式

3、draw.line(xy, options,width) 在[X,Y]之間繪製一條線,options為繪製顏色,width為線條粗細(Note: The width option is broken in 1.1.5. The line is drawn with twice the width you specify. This will be fixed in 1.1.6.)

4、ImageFont.truetype(font=None, size=10, index=0, encoding='', layout_engine=None) 這個是我debug了好久的一個函式,該函式可以載入一個字型,如果電泳出現load error 是因為沒有引用絕對路徑。而且必須呀檢視該路徑下是否存在該字型,size可以設定字型大小

5、draw.text(position, string, options)  繪製字元string在指定的position,option可以選擇顏色、字型outline integer or tuple、fill integer or tuple、font ImageFont instance

6、font.getsize(text)  獲得文字的大小,返回值為(x,y)的元祖,The font option is used to specify which font to use. It should be an instance of the ImageFont class, typically loaded from file using the load method in theImageFont module.

7、im.transform(size, AFFINE, data, filter) ⇒ image 對影象應用仿射變換,並將結果放在具有給定大小的新影象中。

資料是6元組(a,b,c,d,e,f),其包含來自仿射變換矩陣的前兩行。對於輸出影象中的每個畫素(x,y),新值取自輸入影象中的位置(a x + b y + c,d x+ e y + f),舍入到最近的畫素。

此功能可用於縮放,平移,旋轉和剪下原始影象。

8、im.filter(filter) ⇒ image 返回由給定過濾器過濾的影象的副本。有關可用過濾器的列表,在ImageFilter內檢視,提供了多種濾鏡。