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

 

python 生成驗證碼圖片html

來自 《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表示仿射變化
49     # 第三個參數是轉換方法的額外數據, Image.BILINEAR是線性插值法
50     image = image.transform((width+20, height+10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) 51     # 濾鏡,邊界增強,ImageFilter.EDGE_ENHANCE_MORE爲深度邊緣加強濾波,會使得圖像中邊緣部分更加明顯。
52     image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) 53     # 保存驗證碼圖片
54     image.save('idencode.png') 55 
56 
57 if __name__ == "__main__": 58     # 字體的位置
59     font_path = 'FangZhengFangSongJianTi-1.ttf'
60     # 生成幾位數的驗證碼
61     number = 4
62     # 生成驗證碼圖片的高度和寬度
63     size = (80, 30) 64     # 背景顏色,默認爲白色
65     bgcolor = (255, 255, 255) 66     # 字體顏色,默認爲藍色
67     fontcolor = (0, 0, 255) 68     # 干擾線顏色,默認爲紅色
69     linecolor = (255, 0, 0) 70     # 是否加入干擾線
71     draw_line = True 72     # 假如干擾線條數的上/下限
73     line_number = (1, 5) 74     # 調用生成驗證碼diamante
75     gene_code(size, bgcolor, font_path, number, draw_line, fontcolor)

 

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

結果圖:dom

相關文章
相關標籤/搜索