三行 Python 代碼制作圖片驗(yàn)證碼

Pillow庫(kù)
1、Image:含有圖片對(duì)象主體上的一些應(yīng)用 2、ImageDraw:畫(huà)筆,用來(lái)向圖片上添加驗(yàn)證碼 3、ImageFont:設(shè)置驗(yàn)證碼的字體形式 4、ImageFilter:對(duì)圖片驗(yàn)證碼進(jìn)行模糊處理
from?PIL?import?Image,ImageDraw,ImageFont,ImageFilter
import?random,string
#獲取隨機(jī)4個(gè)字符組合
def?getRandomChar():
????chr_all?=?string.ascii_letters+string.digits
????chr_4?=?''.join(random.sample(chr_all,4))
????return?chr_4
#獲取隨機(jī)顏色
def?getRandomColor(low,high):
????return?(random.randint(low,high),random.randint(low,high),random.randint(low,high))
#制作驗(yàn)證碼圖片
def?getPicture():
????width,height?=?180,60
????#創(chuàng)建空白畫(huà)布
????image?=?Image.new('RGB',(width,height),getRandomColor(20,100))
????#驗(yàn)證碼的字體
????font?=?ImageFont.truetype('C:/Windows/fonts/stxinwei.ttf',40)
????#創(chuàng)建畫(huà)筆
????draw?=?ImageDraw.Draw(image)
????#獲取驗(yàn)證碼
????char_4?=?getRandomChar()
????#向畫(huà)布上填寫(xiě)驗(yàn)證碼
????for?i?in?range(4):
????????draw.text((40*i+10,0),char_4[i],font?=?font,fill=getRandomColor(100,200))
????#繪制干擾點(diǎn)
????for?x?in?range(random.randint(200,600)):
????????x?=?random.randint(1,width-1)
????????y?=?random.randint(1,height-1)
????????draw.point((x,y),fill=getRandomColor(50,150))
????#模糊處理
????image?=?image.filter(ImageFilter.BLUR)
????image.save('./%s.jpg'?%?char_4)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

captcha庫(kù)

pip?install?captcha?-i?https://pypi.tuna.tsinghua.edu.cn/simple
from?captcha.image?import?ImageCaptcha
import?random,string
chr_all?=?string.ascii_letters?+?string.digits
chr_4?=?''.join(random.sample(chr_all,?4))
image?=?ImageCaptcha().generate_image(chr_4)
image.save('./%s.jpg'?%?chr_4)

gvcode庫(kù)
pip?install?graphic-verification-code?-i?https://pypi.tuna.tsinghua.edu.cn/simple
import?gvcode
s,v?=?gvcode.generate()
s.save('./%s.jpg'?%?v)
print(type(s))
print(v)
print(type(v))


說(shuō)在最后
Python中文社區(qū)作為一個(gè)去中心化的全球技術(shù)社區(qū),以成為全球20萬(wàn)Python中文開(kāi)發(fā)者的精神部落為愿景,目前覆蓋各大主流媒體和協(xié)作平臺(tái),與阿里、騰訊、百度、微軟、亞馬遜、開(kāi)源中國(guó)、CSDN等業(yè)界知名公司和技術(shù)社區(qū)建立了廣泛的聯(lián)系,擁有來(lái)自十多個(gè)國(guó)家和地區(qū)數(shù)萬(wàn)名登記會(huì)員,會(huì)員來(lái)自以工信部、清華大學(xué)、北京大學(xué)、北京郵電大學(xué)、中國(guó)人民銀行、中科院、中金、華為、BAT、谷歌、微軟等為代表的政府機(jī)關(guān)、科研單位、金融機(jī)構(gòu)以及海內(nèi)外知名公司,全平臺(tái)近20萬(wàn)開(kāi)發(fā)者關(guān)注。
長(zhǎng)按掃碼添加“Python小助手”?
進(jìn)入?P Y 交 流 群
▼點(diǎn)擊成為社區(qū)會(huì)員? ?喜歡就點(diǎn)個(gè)在看吧
評(píng)論
圖片
表情
