Python實現(xiàn)隨機生成圖片驗證碼詳解
使用python生成一個圖片驗證碼,隨機的,可以由于驗證人機和別的啊,很方便很簡單
導(dǎo)入模塊
import random from PIL import Image,ImageFont,ImageDraw
生成隨機驗證碼
def rndtxt():
txt_list = []
# 大寫字母
txt_list.extend([i for i in range(65,90)])
# 小寫字母
txt_list.extend([i for i in range(97,123)])
# 數(shù)字
txt_list.extend([i for i in range(48,57)])
return chr(txt_list[random.randint(0,len(txt_list)-1)])
作為待會生成的圖片背景色和字體色
def rndbgcolor():
# 背景顏色
return (random.randint(64,255),random.randint(64,255),random.randint(64,255))
def rndtxtcolor2():
# 字體顏色
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
進行生成打印驗證碼并以圖片的形式打開,不保存圖片文件,僅用于一時的驗證碼驗證
def code():
weight = 240
hight = 60
image = Image.new('RGB',(weight,hight),(255,255,255))
font = ImageFont.truetype('msyh.ttc',36)
draw = ImageDraw.Draw(image)
# 填充背景顏色
for x in range(weight):
for y in range(hight):
draw.point((x,y),fill=rndbgcolor())
# 生成隨機驗證碼
for T in range(4):
rndtxt_2 = rndtxt()
print(rndtxt_2) # 打印驗證碼的值
draw.text((60 * T + 10,10),rndtxt_2,font=font,fill=rndtxtcolor2())
image.show()
完整代碼:
#!/usr/bin/env python3
import random
from PIL import Image,ImageFont,ImageDraw
def rndtxt():
txt_list = []
# 大寫字母
txt_list.extend([i for i in range(65,90)])
# 小寫字母
txt_list.extend([i for i in range(97,123)])
# 數(shù)字
txt_list.extend([i for i in range(48,57)])
return chr(txt_list[random.randint(0,len(txt_list)-1)])
def rndbgcolor():
# 背景顏色
return (random.randint(64,255),random.randint(64,255),random.randint(64,255))
def rndtxtcolor2():
# 字體顏色
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
def code():
weight = 240
hight = 60
image = Image.new('RGB',(weight,hight),(255,255,255))
font = ImageFont.truetype('msyh.ttc',36)
draw = ImageDraw.Draw(image)
# 填充背景顏色
for x in range(weight):
for y in range(hight):
draw.point((x,y),fill=rndbgcolor())
# 生成隨機驗證碼
for T in range(4):
rndtxt_2 = rndtxt()
print(rndtxt_2) # 打印驗證碼的值
draw.text((60 * T + 10,10),rndtxt_2,font=font,fill=rndtxtcolor2())
image.show()
code()以上就是Python實現(xiàn)隨機生成圖片驗證碼詳解的詳細內(nèi)容,更多關(guān)于Python圖片驗證碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Tensorflow: 從checkpoint文件中讀取tensor方式
今天小編就為大家分享一篇Tensorflow: 從checkpoint文件中讀取tensor方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python使用Py2neo創(chuàng)建Neo4j的節(jié)點和關(guān)系
Neo4j是一款開源圖數(shù)據(jù)庫,使用Python語言訪問Neo4j可以使用Py2neo。本文介紹了使用Py2neo訪問Neo4j,批量創(chuàng)建節(jié)點和關(guān)系的方法2021-08-08
淺談python中統(tǒng)計計數(shù)的幾種方法和Counter詳解
今天小編就為大家分享一篇淺談python中統(tǒng)計計數(shù)的幾種方法和Counter詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
對python 矩陣轉(zhuǎn)置transpose的實例講解
下面小編就為大家分享一篇對python 矩陣轉(zhuǎn)置transpose的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Jupyter導(dǎo)入自定義模塊及導(dǎo)入后TypeError錯誤問題及解決
這篇文章主要介紹了Jupyter導(dǎo)入自定義模塊及導(dǎo)入后TypeError錯誤問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

