當前位置:名人名言大全網 - 祝福短信 - 求python算法生成驗證碼如圖。

求python算法生成驗證碼如圖。

def基因_文本():

source = list(字符串.字母)

對於範圍(0,10)內的索引:

source.append(str(index))

返回“”。加入(隨機。sample (source,number)) # NUMBER是生成驗證碼的位數。

然後我們需要創建壹個圖片,並將其寫入壹個字符串。需要說明的是,裏面的字體依賴於不同的系統。如果找不到系統字體路徑,可以設置。

def基因代碼():

寬度、高度=尺寸#寬度和高度

Image = image.new ('rgba ',(width,height),bgcolor) #創建圖片。

Font = image Font . truetype(Font _ path,25) #驗證碼的字體和字號

Draw = ImageDraw。繪制(圖像)#創建畫筆

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) #填充字符串

接下來,我們將在圖片上繪制壹些幹涉線。

#用於繪制幹涉線

定義基因線(繪制,寬度,高度):

begin = (random.randint(0,寬度),random.randint(0,高度))

end = (random.randint(0,寬度),random.randint(0,高度))

draw.line([begin,end],fill = linecolor)

最後,創建壹個扭曲,並添加壹個過濾器,以增強驗證碼的效果。

Image = Image.transform((寬度+20,高度+10),image.affine,(1,-0.3,0,-0.1,0),image .雙線性)#創建扭曲。

image = image . filter(image filter . edge _ enhance _ more)# filter,邊界增強。

Image.save('idencode.png') #保存驗證碼圖片。