Django---验证码

四种返回前端的方法

现在介绍第四种

import json
import random
from io import BytesIO
from  PIL import Image, ImageDraw, ImageFont

def get_rgb_func():
    """
    获取三原色
    :return: 三个元组
    """
    return (random.randint(1,255),random.randint(1,255),random.randint(1,255))


def get_imge(request):
    image = Image.new(mode="RGB", size=(130, 60), color=get_rgb_func())
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("static/fonts/kumo.ttf",size=36)
    f = BytesIO()
    temp = []
    for i in range(5):
        random_char = random.choice([str(random.randint(0,9)),chr(random.randint(65,90)),chr(random.randint(97,122))])
        draw.text((i*27,10),random_char,get_rgb_func(),font=font)
        temp.append(random_char)
    width = 120
    height = 80

    for i in range(80):
        draw.point((random.randint(0,width),random.randint(0,height)),fill=get_rgb_func())

    for i in range(10):
        x1=random.randint(0,width)
        x2=random.randint(0,width)
        y1=random.randint(0,height)
        y2=random.randint(0,height)
        draw.line((x1,y1,x2,y2),fill=get_rgb_func())
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=get_rgb_func())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_rgb_func())
    image.save(f, "png")
    data = f.getvalue()
    request.session["random_char"] = ''.join(temp)
    return HttpResponse(data)

 

posted @ 2018-02-05 20:19  AndRew-A  阅读(146)  评论(0编辑  收藏  举报