1. 程式人生 > >使用python pillow模組生成隨機驗證碼

使用python pillow模組生成隨機驗證碼

主要用來生成驗證碼,如果要在頁面中使用還要嵌入你所寫的框架`

import random,string
from PIL import Image,ImageDraw,ImageFilter,ImageFont


class check_code(object):
    def __init__(self):
        self.s_list = ''

    # 生成隨機字元
    def rndChar(self):
        s = string.ascii_lowercase + string.ascii_uppercase + string.digits
        return random.choice(s)
    # 生成隨機RGB值
    def rndColor(self):
        return (random.randint(64,255),random.randint(64,255),random.randint(64,255))

    # 生成驗證碼,傳入n表示生成幾位驗證碼
    def new_check_code(self,n):
        width = 60 * n
        heigth = 60
        image = Image.new('RGB',(width,heigth),(255,255,255))
        font = ImageFont.truetype('ARIALBI.TTF',36)
        draw = ImageDraw.Draw(image)
        for x in range(width):
            for y in range(heigth):
                draw.point((x,y),fill = self.rndColor())
        for t in range(n):
            s = self.rndChar()
            self.s_list += s
            draw.text((60*t+10,10),s,font = font,fill = self.rndColor())
        image = image.filter(ImageFilter.BLUR)
       	#  image.show()
     	#  image.save('code2.jpg','jpeg')
        return image

if __name__ == "__main__":
    c = check_code()
    # 這裡接收一下image物件
    image = c.new_check_code(5)
    # 列印一下生成的字串
    print(c.s_list)

`