• 基于PIL模块创建验证码图片


    def get_valid_img(request):
        # 方式2:基于PIL模块创建验证码图片
        from PIL import Image, ImageDraw, ImageFont
        from io import BytesIO
    
        def get_random_color():
            import random
            return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    
        # img=Image.new("RGB",(350,38),get_random_color())
        # f=open("valid.png","wb")
        # img.save(f,"png")
        # with open("valid.png","rb") as f:
        #     data=f.read()
    
        # 方式3:
        # img=Image.new("RGB",(350,38),get_random_color())
        # f=BytesIO()
        # img.save(f,"png")
        # data=f.getvalue()
    
        # # 方式4:完善文本
        #
        # img=Image.new("RGB",(350,38),get_random_color())
        # draw=ImageDraw.Draw(img)
        # font=ImageFont.truetype("static/font/kumo.ttf",32)
        # draw.text((0,0),"python!",get_random_color(),font=font)
        #
        # # 写与读
        # f=BytesIO()
        # img.save(f,"png")
        # data=f.getvalue()
    
        # 方式5:
        #
        img = Image.new("RGB", (170, 35), get_random_color())
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype("static/font/kumo.ttf", 32)
        keep_str = ""
        for i in range(4):
            random_num = str(random.randint(0, 9))
            random_lowalf = chr(random.randint(97, 122))
            random_upperalf = chr(random.randint(65, 90))
            random_char = random.choice([random_num, random_lowalf, random_upperalf])
            draw.text((i * 30 + 30, 0), random_char, get_random_color(), font=font)
            keep_str += random_char
    
        #  加噪点
        width = 170
        height = 35
        for i in range(6):
            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(6):
            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())
        # 写与读
        f = BytesIO()
        img.save(f, "png")
        data = f.getvalue()
        print('keep_str', keep_str)
        # 将验证码存在各自的session中
        request.session['keep_str'] = keep_str
    
        return HttpResponse(data)
  • 相关阅读:
    025-Cinder服务-->安装并配置一个本地存储节点(ISCSI)
    023-OpenStack 创建实例类型临时磁盘的讲解
    addClass+siblings+removeClass用意:
    SublimeText 改变 tab的距离
    正则表达式选取数值
    正则表达式用来根据某种匹配模式寻找字符串中的某些单词。
    hasOwnProperty()函数
    翻转字符串算法
    输入框禁用和启用
    什么是thinkphp
  • 原文地址:https://www.cnblogs.com/zwq-/p/10902589.html
Copyright © 2020-2023  润新知