django项目制作验证码图片

第一步,安装Pillow

pip install Pillow

第二步,创建一个python package,注意,必须有__init__.py文件,然后在windows主机上随意找一个字体文件我这里是simhei.ttf

 第三步,创建一个py文件,内容如下:

import random
from PIL import Image,ImageDraw,ImageFont
import time
import os
import string


#Captcha验证码
class Captcha(object):
    #把常亮抽取成类属性
    #字体的位置
    font_path = os.path.join(os.path.dirname(__file__),'simhei.ttf')
    #生成几位数的验证码
    number = 4
    # 生成验证码的宽度和高度
    size = (100,40)
    # 背景颜色,默认白色RGB(red,green,blue)
    bgcolor = (0,0,0)
    #随机字体颜色
    random.seed(int(time.time()))
    fontcolor = (random.randint(200,255),random.randint(100,255),random.randint(100,255))
    # 验证码字体大小
    fontsize = 20
    # 随机干扰线颜色
    linecolor = (random.randint(0,250),random.randint(0,255),random.randint(0,250))
    #是否要加入干扰线
    draw_line = True
    # 是否回执干扰线
    draw_point = True
    #加入干扰线的条数
    line_number = 3

    SOURCE = list(string.ascii_letters)
    for index in range(0,10):
        SOURCE.append(str(index))

    #用来随机生成一个字符串(包括英文和数字)
    # 定义成类方法,然后是私有的,对象在外面不能直接调用
    @classmethod
    def gene_text(cls):
        return "".join(random.sample(cls.SOURCE,cls.number))

    #用来回执干扰线
    @classmethod
    def __gene_line(cls,draw,width,height):
        begin = (random.randint(0,width),random.randint(0,height))
        end = (random.randint(0,width),random.randint(0,height))
        draw.line([begin,end], fill=cls.linecolor)

    #用来回执干扰点
    @classmethod
    def __gene_points(cls,draw,point_chance,width,height):
        chance = min(100,max(0,int(point_chance)))
        for w in range(width):
            for h in range(height):
                tmp = random.randint(0,100)
                if tmp > 100 - chance:
                    draw.point((w,h),fill=(0,0,0))
    #生成验证码
    @classmethod
    def gene_code(cls):
        width,height = cls.size
        image = Image.new('RGBA',(width,height),cls.bgcolor)#创建画板
        font = ImageFont.truetype(cls.font_path,cls.fontsize)#验证码字体
        draw = ImageDraw.Draw(image)#创建画笔
        text = cls.gene_text()#生成字符串
        font_width,font_height = font.getsize(text)
        draw.text(((width - font_width)/2,(height - font_height)/2),text,font=font,fill=cls.fontcolor)
        if cls.draw_line:
            # 遍历line_number次,就是画line_number根条线
            for x in range(0, cls.line_number):
                cls.__gene_line(draw,width,height)
        #如果要回执噪点
        if cls.draw_point:
            cls.__gene_points(draw,10,width,height)
        return (text,image)

第四步,创建view视图

from utils.captcha.xfzcaptcha import Captcha
from io import BytesIO
def img_captcha(request):
    text,image = Captcha.gene_code()
    # BytesIO相当于一个管道,用来存储图片的流数据
    out = BytesIO()
    # 调用image的save方法,将照片存储到BytesIO中
    image.save(out, 'png')
    # 将BytesIO的文件指针移动到最开始位置
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    # 从BytesIO的管道中,读取出图片数据,保存到response对象上
    response.write(out.read())
    response['Content-length'] = out.tell()
    return response

第五步,创建url路由映射

urlpatterns = [
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('img_captcha/',views.img_captcha, name='img_captcha'),
    path('register/',views.register, name='register')
]

第六步,查看我们的登录页面显示的图片验证码

猜你喜欢

转载自www.cnblogs.com/fengzi7314/p/12735506.html