python創建驗證碼

#python創建驗證碼

import random,string,math
from PIL import Image,ImageFont,ImageDraw,ImageFilter
import matplotlib.pyplot as plt
size=(80,30)#驗證碼寬高
def create_text():
    source=list(string.ascii_letters)
    for i in range(0,10):
        source.append(str(i))#加入數字
    return  "".join(random.sample(source,4))#返回四位
#干擾線
def  disturb_line(draw,width,height):
    for j in range(0,5):
        begin = (random.randint(0, width), random.randint(0, height))  # 元組
        end = (random.randint(0, width), random.randint(0, height))
        draw.line([begin, end], fill=(255, 0, 0))  # 紅色干擾線
#生成驗證碼
def  result():
    width,height=size#不需要全局
    image=Image.new("RGBA",size,(255,255,255))#背景默認白色
    font=ImageFont.truetype("C:\Windows\Fonts\simfang.ttf",25)#字體選擇
    draw=ImageDraw.Draw(image)#畫筆
    text=create_text()
    font_w,font_h=font.getsize(text)
    draw.text(((width-font_w)//4,(height-font_h)//4),text,fill=(0,0,255),font=font)

    disturb_line(draw,width,height)#干擾,傳入畫筆類

    image=image.transform((width+10,height+5),Image.AFFINE,(1,0.1,-0.1,0,1,0),Image.BILINEAR)#雙線性
    #第三行默認0,0,1
    image=image.filter(ImageFilter.EDGE_ENHANCE_MORE)
    plt.imshow(image)
    plt.show()

if __name__=="__main__":
    result()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章