生成图片验证码

def get_validCode_img(request):


    # 方式1:
    # import os
    # path= os.path.join(settings.BASE_DIR,"blog","static","img","tom.jpg")
    #
    # with open(path,"rb") as f:
    #     data=f.read()

    # 方式2:
    # from  PIL import Image
    #
    # img=Image.new(mode="RGB",size=(120,40),color="green")
    #
    # f=open("validCode.png","wb")
    # img.save(f,"png")
    #
    # with open("validCode.png","rb") as f:
    #     data=f.read()

    # 方式3:
    # from io import BytesIO
    #
    # from PIL import Image
    # img = Image.new(mode="RGB", size=(120, 40), color="blue")
    # f=BytesIO()
    # img.save(f,"png")
    # data=f.getvalue()
    # return HttpResponse(data)

    # 方式4 :

    from io import BytesIO
    import random

    from PIL import Image,ImageDraw,ImageFont
    img = Image.new(mode="RGB", size=(120, 40), color=(random.randint(0,255),random.randint(0,255),random.randint(0,255)))

    draw=ImageDraw.Draw(img,"RGB")  # 创建一个队img图片对象,进行操作的对象
    font=ImageFont.truetype("blog/static/font/kumo.ttf",25)

    valid_list=[]
    for i in range(5):

        random_num=str(random.randint(0,9))
        random_lower_zimu=chr(random.randint(65,90))
        random_upper_zimu=chr(random.randint(97,122))

        random_char=random.choice([random_num,random_lower_zimu,random_upper_zimu])
        draw.text([5+i*24,10],random_char,(random.randint(0,255),random.randint(0,255),random.randint(0,255)),font=font)
        valid_list.append(random_char)


    f=BytesIO()
    img.save(f,"png")
    data=f.getvalue()

    valid_str="".join(valid_list)
    print(valid_str)

    request.session["keepValidCode"]=valid_str   # 把生成的验证码保留一份,用于用户在前端输入之后,进行比对

    return HttpResponse(data)

阅读更多

没有更多推荐了,返回首页