您好,欢迎访问一九零五行业门户网

python3 pillow生成验证码图片方法介绍

本篇文章主要介绍了python3 pillow生成简单验证码图片的示例,非常具有实用价值,需要的朋友可以参考下
使用python的pillow模块 random 模块随机生成验证码图片,并应用到django项目中
安装pillow
$ pip3 install pillow
生成验证码图片
\vericode.py from pil import image,imagedraw,imagefont,imagefilter import random #随机码 默认长度=1 def random_code(lenght=1): code = '' for char in range(lenght): code += chr(random.randint(65,90)) return code #随机颜色 默认颜色范围【1,255】 def random_color(s=1,e=255): return (random.randint(s,e),random.randint(s,e),random.randint(s,e)) #生成验证码图片 #length 验证码长度 #width 图片宽度 #height 图片高度 #返回验证码和图片 def veri_code(lenght=4,width=160,height=40): #创建image对象 image = image.new('rgb',(width,height),(255,255,255)) #创建font对象 font = imagefont.truetype('arial.ttf',32) #创建draw对象 draw = imagedraw.draw(image) #随机颜色填充每个像素 for x in range(width): for y in range(height): draw.point((x,y),fill=random_color(64,255)) #验证码 code = random_code(lenght) #随机颜色验证码写到图片上 for t in range(lenght): draw.text((40*t+5,5),code[t],font=font,fill=random_color(32,127)) #模糊滤镜 image = image.filter(imagefilter.blur) return code,image
应用
编写django应用下的视图函数
\views.py from . import vericode.py from io import bytesio from django.http import httpresponse def verify_code(request): f = bytesio() code,image = vericode.veri_code() image.save(f,'jpeg') request.session['vericode'] = code return httpresponse(f.getvalue()) def submit_xxx(request): if request.method == "post": vericode = request.session.get("vericode").upper() submitcode = request.post.get("vericode").upper() if submitcode == vericode: return httpresponse('ok') return httpresponse('error')
这里使用了django的session,需要在django settings.py的installed_apps中添加'django.contrib.sessions'(默认添加)
verify_code视图函数将验证码添加到session中和验证码图片一起发送给浏览器,当提交表单到submit_xxx()时,先从session中获取验证码,再对比从表单中的输入的验证码。
这里只是简单说明,url配置和前端代码未给出。
以上就是python3 pillow生成验证码图片方法介绍的详细内容。
其它类似信息

推荐信息