1. 程式人生 > 實用技巧 >python 生成驗證碼圖片(python generate captCHA images)

python 生成驗證碼圖片(python generate captCHA images)

python 生成驗證碼圖片

來自《Python專案案例開發從入門到實戰》(清華大學出版社 鄭秋生 夏敏捷主編)中影象處理——生成二維碼和驗證碼

 1 import random
 2 import string
 3 from PIL import Image, ImageDraw, ImageFont, ImageFilter
 4 
 5 
 6 # 用來隨機生成一個字串
 7 def gene_text(number):
 8     # 生成52個大小寫英文字母
 9     source = list(string.ascii_letters)
10     #
新增上數字 11 for index in range(0, 10): 12 source.append(str(index)) 13 return ''.join(random.sample(source, number)) # number是生成驗證碼的位數 14 15 16 # 用來繪製干擾線 17 def gene_line(draw, width, height, linecolor): 18 # random.randint(a, b)用於生成一個指定範圍內的證書,其中第一個引數a是上限,第二個引數b是下限,生成的隨機數n:a<=n<=b
19 begin = (random.randint(0, width), random.randint(0, height)) 20 end = (random.randint(0, width), random.randint(0, height)) 21 # 在影象上畫線,引數值為線的起始和終止位置座標[(x, y), (x, y)]和線的填充顏色 22 draw.line([begin, end], fill=linecolor) 23 24 25 # 生成驗證碼 26 def gene_code(size, bgcolor, font_path, number, draw_line, fontcolor):
27 # 寬和高 28 width, height = size 29 # 建立圖片, 'RGBA'表示4*8位畫素,真彩+透明通道 30 image = Image.new('RGBA', (width, height), bgcolor) 31 # 驗證碼的字型。ImageFont這個函式從指定的檔案載入了一個字型物件,並且為指定大小的字型建立了字型物件。 32 font = ImageFont.truetype(font_path, 25) 33 # 建立畫筆,建立可用於繪製給定影象的物件 34 draw = ImageDraw.Draw(image) 35 # 隨機生成想要的字串 36 text = gene_text(number) 37 # 返回給定文字的寬度和高度,返回值為2元組 38 font_width, font_height = font.getsize(text) 39 # 填充字串,引數分別是:文字的左上角座標,文字內容,字型,文字的填充顏色 40 draw.text(((width-font_width)/number, (height-font_height)/number), text, font=font, fill=fontcolor) 41 42 if draw_line: 43 # 計算要畫的線的條數 44 line_count = random.randint(line_number[0], line_number[1]) 45 print('line_count = ', line_count) 46 for i in range(line_count): 47 gene_line(draw, width, height, linecolor) 48 # 建立扭曲,transform(size, method, data) 其中第一個引數是尺寸大小, Image.AFFINE表示仿射變化, Image.BILINEAR是線性插值法 49 image = image.transform((width+20, height+10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) 50 # 濾鏡,邊界加強,ImageFilter.EDGE_ENHANCE_MORE為深度邊緣增強濾波,會使得影象中邊緣部分更加明顯。 51 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) 52 # 儲存驗證碼圖片 53 image.save('idencode.png') 54 55 56 if __name__ == "__main__": 57 # 字型的位置 58 font_path = 'FangZhengFangSongJianTi-1.ttf' 59 # 生成幾位數的驗證碼 60 number = 4 61 # 生成驗證碼圖片的高度和寬度 62 size = (80, 30) 63 # 背景顏色,預設為白色 64 bgcolor = (255, 255, 255) 65 # 字型顏色,預設為藍色 66 fontcolor = (0, 0, 255) 67 # 干擾線顏色,預設為紅色 68 linecolor = (255, 0, 0) 69 # 是否加入干擾線 70 draw_line = True 71 # 假如干擾線條數的上/下限 72 line_number = (1, 5) 73 # 呼叫生成驗證碼diamante 74 gene_code(size, bgcolor, font_path, number, draw_line, fontcolor)

其中字型下載的是方正仿宋簡體

結果圖: