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 API 自动化实战详解(纯代码)

Python API 自动化实战详解(纯代码)

主要讲如何在公司利用Python 搞API自动化。 1.分层设计思路 dataPool :数据池层,里面有我们需要的各种数据,包括一些公共数据等 config :基础配置 tools :...

Python的numpy库下的几个小函数的用法(小结)

numpy库是Python进行数据分析和矩阵运算的一个非常重要的库,可以说numpy让Python有了matlab的味道 本文主要介绍几个numpy库下的小函数。 1、mat函数 mat...

下载给定网页上图片的方法

复制代码 代码如下: # -*- coding: utf-8 -*- import re import urllib def getHtml(url): #找出给出网页的源码 page...

python内存管理机制原理详解

python内存管理机制原理详解

python内存管理机制: 引用计数 垃圾回收 内存池 1. 引用计数 当一个python对象被引用时 其引用计数增加 1 ; 当其不再被变量引用时 引用计数减 1...

Python实现配置文件备份的方法

本文实例讲述了Python实现配置文件备份的方法。分享给大家供大家参考。具体如下: 这里平台为Linux: #!/usr/bin/python #Author:gdlinjianyi...