使用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)

`

你可能感兴趣的:(python)