利用PIL生成图片验证码

利用pillow生成图片验证码

安装pillow

pip install pillow

导入模块

from PIL import Image, ImageDraw, ImageFont

生成图片验证码

  • 创建图片
img = Image.new(mode="RGB", size=(120, 40), color="white")
#这里需要三个参数,第一个是指定mode,这里使用RGB模式,第二个指定的图片尺寸,第三个指定图片颜色
  • 创建一个画笔对象
draw = ImageDraw.Draw(img, "RGB")  # 实例画笔对象
#这里的两个参数,第一个是指定一块画布(个人理解,在什么地方开始你的创作),第二个同上mode
  • 指定字体样式和大小
font = ImageFont.truetype("static/font/kumo.ttf", 25)  
# 指定字体样式和大小,这里用的是kumo.ttf这个样式(需要下载),参数一文件的路径,参数二字体大小

详细代码

def get_validCode(request):
    width = 120#指定图片的长高
    height = 40

    def rndColor():
        """
        生成随机颜色
        :return:
        """
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

    img = Image.new(mode="RGB", size=(width, height), color="white")
    draw = ImageDraw.Draw(img, "RGB")  # 实例画笔对象
    font = ImageFont.truetype("static/font/kumo.ttf", 25)  # 指定字体样式和大小
    valid_list = []  # 用于存储随机验证码
    for i in range(5):  # 生成5位数的随机字符
        random_num = str(random.randint(0, 9))  # 随机数字
        random_lower = chr(random.randint(65, 90))  # 随机小写字母
        random_upper = chr(random.randint(97, 122))  # 随机小写字母

        random_char = random.choice([random_num, random_lower, random_upper])  # 随机选择

        draw.text([5 + i * 24, 10], random_char, rndColor(), font=font)
        # 这里列表里的两个参数表示横纵坐标,在img里面的,第二个参数表示文本内容,第三个是颜色,第四个是字体大小
        valid_list.append(random_char)  # 将随机生成的验证码字符串添加到列表中
    for i in range(100):  # 加噪点
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
    for i in range(5):  # 加干扰线,这里通过添加多组横纵坐标实现
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
        x3 = random.randint(0, width)
        y3 = random.randint(0, height)

        draw.line((x1, y1, x2, y2, x3, y3), fill=rndColor())
    f = BytesIO()  # 相当于获取文件句柄
    img.save(f, "png")  # 存入内存,以png的格式
    data = f.getvalue()  # 从内存中取出来

    valid_str = "".join(valid_list)  # 转化成随机的字符串格式

    request.session["keepValidCode"] = valid_str  # 将随机字符串放入session中
    return HttpResponse(data)#这里需要交给前端的ajax处理

前端代码

{##}//这里写了一个简单的登录页面
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/sweet/sweetalert2.min.css">
    <script src="/static/js/jquery-3.2.1.min.js">script>
    <script src="/static/js/bootstrap.min.js">script>
    <script src="/static/js/jquery.cookie.js">script>
    <script src="/static/sweet/sweetalert2.min.js">script>

head>
<body style="background-color: #f8f8f8">
<div class="container   col-md-4 col-lg-offset-4 ">

    <div class="panel panel-info " style="margin-top: 100px">
        <div class="panel-heading" style="padding: 5px 0">
            <h4 class="text-center">请登录h4>
        div>
        <div class="row">
            <div class="panel-body col-md-10 col-md-offset-1">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group user">
                        <label for="exampleInputEmail1">用户名:label>
                        <input type="text" class="form-control" id="exampleInputEmail1">
                        <span id="helpBlock2" class="help-block">span>
                    div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">密码:label>
                        <input type="password" class="form-control" id="exampleInputPassword1">
                        <span id="helpBlock3" class="help-block">span>
                    div>
                    <div class="row">
                        <div class="form-group  col-md-6">
                            <label for="validateCode">验证码:label>
                            <input type="password" class="form-control" id="validateCode">
                            <span id="helpBlock4" class="help-block">span>
                        div>
                        <div class="col-md-6">
                            <img src="/get_validCode/" alt="" width="150px" height="40px" style="margin-top: 20px;" id="imgCode">
                        div>
                    div>

                    <div class="form-group">
                        <span class="failed" style="color: red">span>
                    div>
                    <div class="form-group col-lg-offset-4 col-md-4">
                        <input type="button" value="登  录" class="form-control btn-primary" id="login">

                    div>

                form>
                <div class="from-group">
                    <span class="form-group pull-right"><span>还没有账号?<a href="/register/">点击注册a>span>span>
                div>
            div>

        div>
    div>

div>
<script>
{#    $("#imgCode").on("click",function () {#}
{#        $(this)[0].src += "?"#}
{#    });#}
$("#imgCode").on("click",function () {
    $.ajax({
        url: "/get_validCode/",
        type: "GET",
        success: function (data) {
            $("#imgCode").attr("src", "/get_validCode/")
        }

    })
});





$("#login").on("click", function () {

        $.ajax(
                {
                    url: "/sign_in/",
                    type: "POST",
                    headers: {"X-CSRFToken": $.cookie('csrftoken')},
                    data: {
                        user: $("#exampleInputEmail1").val(),
                        pwd: $("#exampleInputPassword1").val(),
                        validCode:$("#validateCode").val()

                    },
                    success: function (data) {

                        var dat = JSON.parse(data);

                        if (dat["state"] == "success") {
                            swal(
                                    '',
                                    '登录成功,正在跳转...',
                                    'success'
                            );
                            setTimeout(function () {
                                window.location.href = "/index/";
                            }, 3000);

                        }
                        if (dat["state"] == "user_none") {
                            $("#exampleInputEmail1").focus();
                            var use = $("#helpBlock2");
                            use.parent().addClass("has-error");
                            use.html("请输入用户名")
                        }
                        if (dat["state"] == "pwd_none") {
                            $("#exampleInputPassword1").focus();
                            var pwd = $("#helpBlock3");
                            pwd.parent().addClass("has-error");
                            pwd.html("请输入登录密码")
                        }
                        if (dat["state"] == "validCode_none"){
                            $("#validateCode").focus();
                            var valid = $("#helpBlock4");
                            valid.parent().addClass("has-error");
                            valid.html("请输入验证码")
                        }
                        if (dat["state"] == "validCode_error"){
                            $("#validateCode").focus();
                            var valid_error = $("#helpBlock4");
                           valid_error.parent().addClass("has-error");
                            valid_error.html("验证码错误")
                        }
                        if (dat["state"] == "failed") {

                            swal(
                                    '',
                                    '用户名或密码错误',
                                    'error'
                            )
                        }


                    }
                }
        )
    });
script>
body>
html>

视图函数

def sign_in(request):#貌似写的太啰嗦了,登录的函数
    if request.method == "GET":
        return render(request, "login.html")

    elif request.method == "POST":
        state = {"state": None}
        username = request.POST.get("user")
        if username == "":
            state["state"] = "user_none"
            return HttpResponse(json.dumps(state))
        password = request.POST.get("pwd")
        if password == "":
            state["state"] = "pwd_none"
            return HttpResponse(json.dumps(state))

        validCode = request.POST.get("validCode")
        if validCode == "":
            state["state"] = "validCode_none"
            return HttpResponse(json.dumps(state))
        if validCode.upper() == request.session.get("keepValidCode").upper():
            user = auth.authenticate(username=username, password=password)
            if user:
                state["state"] = "success"
                auth.login(request, user)
            else:
                state["state"] = "failed"
            return HttpResponse(json.dumps(state))
        else:
            state["state"] = "validCode_error"
        return HttpResponse(json.dumps(state))

你可能感兴趣的:(django,验证码)