图形验证码
有一个生成验证码的接口
- 要有画布
- 再有画笔
- 还要有字体
- 前提已安装Pillow
1 验证码接口
from random import randint, choice
from PIL import Image, ImageDraw, ImageFont
from io import StringIO,BytesIO
from string import printable
def create_captcha():
font_path = "utils/captcha/font/Arial.ttf"
font_color = (randint(150, 200), randint(0, 150), randint(0, 150))
line_color = (randint(0, 150), randint(0, 150), randint(150, 200))
point_color = (randint(0, 150), randint(50, 150), randint(150, 200))
width, height = 100, 40
image = Image.new('RGB', (width, height), (200, 200, 200))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font_path, height - 10)
text = ''.join([choice(printable[:62]) for i in range(4)])
draw.text((10, 10), text, font=font, fill=font_color)
for i in range(0, 5):
draw.line(((randint(0, width), randint(0, height)),
(randint(0, width), randint(0, height))),
fill=line_color, width=2)
for i in range(randint(100, 1000)):
draw.point((randint(0, width), randint(0, height)), fill=point_color)
out = BytesIO()
image.save(out, format='jpeg')
content = out.getvalue()
out.close()
print('图型验证码', text)
return text, content
2 视图函数
from django.http import HttpResponse
from utils.captcha.captcha import create_captcha
def img_captcha(request):
"""03图形验证码"""
text,image = create_captcha()
request.session['captchar'] = text
request.session.set_expiry(10)
return HttpResponse(image,content_type='image/png')
3 js文件
$(function(){
var imgCaptcha = $('.img-captcha');
imgCaptcha.click(function () {
imgCaptcha.attr("src",'/account/img_captcha'+"?random="+Math.random());
});
});
4 html页面
<img src="{% url 'account:img_captcha'%}" alt="" class="img-captcha input-group-addon"
style="cursor: pointer;">