zoukankan      html  css  js  c++  java
  • python之页面验证码

    一,准备阶段

      安装pillow 模块

    pip install pillow

    二,使用

    from PIL import Image, ImageDraw,ImageFont
    from io import BytesIO
    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", (200, 35), get_random_color())
    
        # 生成随机字符
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype("./static/font/kumo.ttf", size=25)
        print(font,"font")
        temp = []
        for i in range(5):
            random_num = str(random.randint(0, 9))
            random_low = chr(random.randint(97, 122))
            random_upper_alpha = chr(random.randint(65, 90))
            random_char = random.choice([random_num, random_low, random_upper_alpha])
            draw.text((30 + i * 30, 3), random_char, get_random_color(), font=font)
    
            temp.append(random_char)
    
    
            # 噪点噪线
            width=100
            height=40
            for i in range(1):
                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(1):
                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()
        image.save(f, "png")
        data = f.getvalue()
        f.close()
    
        temp_str = "".join(temp)
       # 存入session中方便在其他视图函数中验证 
        request.session["temp_str"] = temp_str
    
        return HttpResponse(data)
    View
    html
      <h1>验证码</h1>
      <img id="valid_img" src="/get_valid_img" alt="验证码加载异常" height="50px" width="300px">
      # 点击刷新验证码
      <script>
        $("#valid_img").cilck(function(){
          $(this)[0].src=$(this)[0].src+"?"
    })


    </script>
    url.py
      url(r'^get_valid_img', views.get_valid_img)

     字体文件下载:点击这里!

  • 相关阅读:
    查准率(precision)和查全率(recall)
    数据集大全:25个深度学习的开放数据集
    利用贝叶斯算法实现手写体识别(Python)
    KNN算法识别手写数字
    判断点在直线的左右哪一侧
    多节点bigchaindb集群部署
    java 多线程 3 synchronized 同步
    java 多线程 1 “常用的实现多线程的2种方式”:Thread 和 Runnable
    java 字符串
    java 关键字static
  • 原文地址:https://www.cnblogs.com/glf1160/p/11109993.html
Copyright © 2011-2022 走看看