IT 全栈开发

python 生成 验证码 图片

2018-04-01  本文已影响5人  醋留香

# 生成随机验证码

def identificode(request):

    aaa = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','j','k','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','J','K','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

    bg= (0 , 255 ,200)

    backcolor= (random.randint(32, 128), random.randint(32, 128), random.randint(32, 128))

    w = 60 * 4;

    h = 60

    # 创建一张图片,指定图片mode,长宽

    image = Image.new('RGB', (w, h), (255,182,193))

    # 设置字体类型及大小

    font = ImageFont.truetype(font='arial.ttf', size=36)

    # 创建Draw对象

    draw = ImageDraw.Draw(image)

    # 将随机生成的chr,draw如image

    global xx;

    xx = "";

    # 遍历给图片的每个像素点着色

    for x in range(w):

        for y in range(h):

            draw.point((x, y),fill=bg)

    for t in range(4):

        a=aaa[random.randint(0 , 57)];

        xx=xx+a;

        draw.text((60 * t + 10, 10), a, font=font,fill=backcolor)

    xx=str.lower(xx);#大写字母转小写

    image = image.filter(ImageFilter.BLUR)

    image.save('./shopApp/static/myfile/code.jpg', 'jpeg')

    imgDic = {"imgPath":"static/myfile/code.jpg"}

    return HttpResponse(json.dumps(imgDic) , content_type = "application/json")

上一篇 下一篇

猜你喜欢

热点阅读