python3 pillow生成简单验证码图片的示例

yipeiwu_com6年前Python基础

使用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配置和前端代码未给出。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python cookbook(数据结构与算法)实现优先级队列的方法示例

本文实例讲述了Python实现优先级队列的方法。分享给大家供大家参考,具体如下: 问题:要实现一个队列,它能够以给定的优先级对元素排序,且每次pop操作时都会返回优先级最高的那个元素;...

用实例分析Python中method的参数传递过程

什么是method? function就是可以通过名字可以调用的一段代码,我们可以传参数进去,得到返回值。所有的参数都是明确的传递过去的。 method是function与对象的结合。我...

对Python中数组的几种使用方法总结

二维数组的初始化 matirx_done = [[0 for i in range(0, len(matirx))]for j in range(0, len(matirx[0]))...

python寻找list中最大值、最小值并返回其所在位置的方法

实例如下所示: c = [-10,-5,0,5,3,10,15,-20,25] print c.index(min(c)) # 返回最小值 print c.index(max(c)...

【python】matplotlib动态显示详解

【python】matplotlib动态显示详解

1.matplotlib动态绘图 python在绘图的时候,需要开启 interactive mode。核心代码如下: plt.ion(); #开启interactive mode...