利用io模块和PIL生成图片验证码

直接贴代码

import random
from django.shortcuts import HttpResponse
from io import BytesIO
from PIL import ImageDraw, ImageFont, Image


# 获取验证码
def inputimg(request):
    # 生成随机颜色
    def get_random_color():
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    # BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes
    f = BytesIO()
    # 创建新的图片,指定打下颜色
    image = Image.new(mode="RGB", size=(160, 35), color=get_random_color())
    # 创建一个可以在给定图像上绘图的对象。
    draw = ImageDraw.Draw(image)
    # 设置字体及大小
    font = ImageFont.truetype("static/fonts/kumo.ttf", size=36)

    temp = []
    for i in range(5):
        # 生成随机字符
        random_char = random.choice(
            [str(random.randint(0, 9)), chr(random.randint(65, 90)), chr(random.randint(97, 122))])
        # 将字符绘入图片
        draw.text((i * 30, 0), random_char, get_random_color(), font=font)
        # 将字符添加进列表中
        temp.append(random_char)

    width = 120
    height = 80

    # for i in range(80):
    #     # 绘制点
    #     draw.point((random.randint(0,width),random.randint(0,height)),fill=get_random_color())
    #
    # for i in range(10):
    #     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(50):
        # 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
    image.save(f, "png")
    # 读取f
    data = f.getvalue()
    # 设置session,保存为浏览器发送的随机字符
    request.session["random_code_str"] = "".join(temp)
    return HttpResponse(data)

验证码刷新

只需要在图片的url时候加上一个?,他就会重新加载图片

 $('#img').click(function () {
        $(this)[0].src+="?"
    });

  

posted @ 2018-02-06 08:27  瓜田月夜  阅读(307)  评论(0)    收藏  举报