python如何生成网页验证码

yipeiwu_com6年前Python基础

本文实例为大家分享了python生成网页验证码的具体代码,供大家参考,具体内容如下

验证码为pil模块生成,可直接应用于django框架当中。

首先需要安装Pillow模块 我们这里使用的版本为3.4.1
终端中直接输入指令 pip install Pillow==3.4.1

from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO

def verify_code(request):
  #引入随机函数模块
  import random
  #定义变量,用于画面的背景色、宽、高
  bgcolor = (random.randrange(20, 100), random.randrange(
    20, 100), 255)
  width = 100
  height = 25
  #创建画面对象
  im = Image.new('RGB', (width, height), bgcolor)
  #创建画笔对象
  draw = ImageDraw.Draw(im)
  #调用画笔的point()函数绘制噪点
  for i in range(0, 100):
    xy = (random.randrange(0, width), random.randrange(0, height))
    fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
    draw.point(xy, fill=fill)
  #定义验证码的备选值
  str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
  #随机选取4个值作为验证码
  rand_str = ''
  for i in range(0, 4):
    rand_str += str1[random.randrange(0, len(str1))]
  #构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
  font = ImageFont.truetype('FreeMono.ttf', 23)
  #构造字体颜色
  fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
  #绘制4个字
  draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
  draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
  draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
  draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
  #释放画笔
  del draw
  #存入session,用于做进一步验证
  request.session['verifycode'] = rand_str
  #内存文件操作
  buf = BytesIO()
  #将图片保存在内存中,文件类型为png
  im.save(buf, 'png')
  #将内存中的图片数据返回给客户端,MIME类型为图片png
  return HttpResponse(buf.getvalue(), 'image/png'

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

相关文章

numpy ndarray 取出满足特定条件的某些行实例

在进行物体检测的ground truth boxes annotations包围框坐标数据整理时,需要实现这样的功能: numpy里面,对于N*4的数组,要实现对于每一行,如果第3列和第...

Python3实现转换Image图片格式

前言 首先图片格式转换的方法有很多,但是转二进制字节流的,我搜了一下午终于在 stackoverflow上搜到了 说一下为什么要在线转这个图片格式 额,一名Python3 spid...

Python实现的读取电脑硬件信息功能示例

本文实例讲述了Python实现的读取电脑硬件信息功能。分享给大家供大家参考,具体如下: 上学那会,老师让我用java获取电脑硬件信息,CPU, 硬盘,MAC等,那个时候感觉搞了好久。。。...

Python中用Decorator来简化元编程的教程

少劳多得 Decorator 与 Python 之前引入的元编程抽象有着某些共同之处:即使没有这些技术,您也一样可以实现它们所提供的功能。正如 Michele Simionato 和我在...

Python3实现汉语转换为汉语拼音

Python3实现汉语转换为汉语拼音

本文实例为大家分享了Python3实现汉语转换为汉语拼音的具体代码,供大家参考,具体内容如下 工具: Python3.6.2,pycharm 1.使用了 第三方模块 pypinyin(点...