zoukankan      html  css  js  c++  java
  • 自定义的验证码

    from PIL import Image
    from PIL import ImageDraw, ImageFont
    import random
    
    
    def get_valid_img(request):
    
        def get_random_color():
            return (random.randint(0, 255),
                    random.randint(0, 255),
                    random.randint(0, 255))
    
        image = Image.new("RGB", (250, 40), get_random_color())
    
        # 生成五个随机字符
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype("static/blog/font/kumo.ttf", size=32)
        temp = []
        for i in range(5):
            random_num = str(random.randint(0, 9))
            random_low_alpha = chr(random.randint(97, 122)) #得到A~Z
            random_upper_alpha = chr(random.randint(65, 90)) #得到a~z
            random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
            draw.text((24+i*36, 0), random_char, get_random_color(), font=font)
            # 保存随机字符
            temp.append(random_char)
    
        # 噪点噪线
        # width=250
        # height=40
        # for i in range(100):
        #     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_random_color())
        #
        # for i in range(400):
        #     draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
        #     x = random.randint(0, width)
        #     y = random.randint(0, height)
        #     draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
    
        # 在内存生成图片
        from io import BytesIO
        f = BytesIO()
        image.save(f, "png")
        data = f.getvalue()
        f.close()
    
        valid_str = "".join(temp)
        print("valid_str", valid_str)
        # 设置session
        request.session["valid_str"] = valid_str
    
        return data
  • 相关阅读:
    浏览器能正常访问的url,superagent不能正常访问
    Reactor模式理解
    牛客网剑指offer 二维数组的查找
    在C语言结构体中添加成员函数
    html页面字体相关
    html页面背景设定相关
    快速排序
    html页面边框的另一种写法
    2018暑期北航软件能力培养师资培训有感
    web.xml文件介绍
  • 原文地址:https://www.cnblogs.com/Alone-Tree/p/9785804.html
Copyright © 2011-2022 走看看