Python實現隨機生成圖片驗證碼詳解

使用python生成一個圖片驗證碼,隨機的,可以由於驗證人機和別的啊,很方便很簡單

導入模塊

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)])
    # 數字
    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)])
    # 數字
    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實現隨機生成圖片驗證碼詳解的詳細內容,更多關於Python圖片驗證碼的資料請關註WalkonNet其它相關文章!

推薦閱讀: