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

yipeiwu_com7年前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文件读写操作与linux shell变量命令交互执行的方法

本文实例讲述了python文件读写操作与linux shell变量命令交互执行的方法。分享给大家供大家参考。具体如下: python对文件的读写还是挺方便的,与linux shell的交...

pandas将多个dataframe以多个sheet的形式保存到一个excel文件中

要实现这个功能,可能有多种方法,我在这里记录下一个比较方便的方法: import pandas as pd writer = pd.ExcelWriter('test.xlsx')...

Python循环实现n的全排列功能

描述: 输入一个大于0的整数n,输出1到n的全排列: 例如: n=3,输出[[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2]...

深入浅析python继承问题

有如下的代码: class p1: def __init__(self,a,b): print("init in p1") self.a1=a self.b1=b self.f1()...

Python中return self的用法详解

在Python中,有些开源项目中的方法返回结果为self. 对于不熟悉这种用法的读者来说,这无疑使人困扰,本文的目的就是给出这种语法的一个解释,并且给出几个例子。 在Python中,re...