python 用 PIL 模块 画验证码

PIL 简单绘画

def get_code_img(request):
    from PIL import Image, ImageDraw, ImageFont
    import random

    def random_color():
        '''元组 (255,255,255)'''
        return (random.randint(0,255),random.randint(0,255),random.randint(0,255))

    def random_char():
        '''传入需生成字符的个数,返回列表'''
        temp = []
        for i in range(4):
            a = chr(random.randint(65, 90))     # 生成大写字母
            b = chr(random.randint(97, 122))    # 生成小写字母
            c = str(random.randint(0, 9))       # 生成数字,注意要转换成字符串类型
            temp.append(random.choice([a,b,c]))
        return temp

    def create_lines():
        '''干扰线'''
        size=(200,40)
        for i in range(random.randint(2,7)):
            begin = (random.randint(0,size[0]),random.randint(0,size[1]))
            end = (random.randint(0,size[0]),random.randint(0,size[1]))
            draw_obj.line((begin,end),fill=random_color(),width=random.randint(1,4))

    def create_point():
        '''干扰点'''
        for i in range(80):
            draw_obj.point((random.randint(0, 220), random.randint(0, 40)), fill=random_color())
            x = random.randint(0,220)
            y = random.randint(0,40)
            z = random.randint(1,7)
            a = random.randint(0,270)
            b = random.randint(60,360)
            draw_obj.arc((x, y, x+z, y+z), 0, 360, fill=random_color())
    # 生成一个图片对象
    img_obj = Image.new('RGB',(220,40),random_color())
    #生成画笔对象
    draw_obj = ImageDraw.Draw(img_obj)
    # 生成字体对象
    font_obj = ImageFont.truetype('static/fonts/kumo.ttf', 40)
    # 将字符画到图片上
    char_list = random_char()
    # print(''.join(char_list))
    request.session["code_img"] = "".join(char_list)
    for i in range(len(char_list)):
        draw_obj.text((10+50*i,0),char_list[i],fill=random_color(),font=font_obj)
    create_lines()
    create_point()
    # img_obj.show()    # 调用默认图片浏览器查看

    # 不需要在硬盘上保存文件,直接在内存中加载就可以
    from io import BytesIO
    io_obj = BytesIO()
    # 将生成的图片数据保存在io对象中
    img_obj.save(io_obj, "png")
    # 从io对象里面取上一步保存的数据
    data = io_obj.getvalue()
    return HttpResponse(data)



<div class="form-group">
    <label for="check_code" class="col-sm-2 control-label">验证码</label>
    <div class="col-sm-7 row">
        <div class="col-sm-4">
            <input id="check_code" name="check_code" type="text" class="form-control"/>
        </div>
        <div style="border-radius: 4px;overflow: hidden;">
            <img id="get_code" src="/get_code_img/" alt="验证码加载失败">
        </div>
    </div>
</div>
<script>
    $('#get_code').click(function () {
        // 点击图片刷新验证码
        $(this)[0].src += "?";
    });

    $('#check_code').focus(function () {
        $('#error_msg').text('')
    })
</script>

 

posted @ 2018-10-22 02:20  ming-yuan  阅读(369)  评论(0编辑  收藏  举报