生成随机验证码:

# -*- coding: utf-8 -*-
# @Author: huangyong
# @Date: 2016-10-29 22:18:38
# @Last Modified by: Administrator
# @Last Modified time: 2016-11-21 20:08:31
import random
# pip install Pillow
# Image:是一个画板(context),ImageDraw:是一个画笔, ImageFont:画笔的字体
from PIL import Image, ImageDraw, ImageFont
import time
import os
import string # Captcha验证码 class Captcha(object):
# 把一些常量抽取成类属性
# 字体的位置
font_path = os.path.join(os.path.dirname(__file__), 'verdana.ttf')
# font_path = 'utils/captcha/verdana.ttf'
# 生成几位数的验证码
number = 4
# 生成验证码图片的宽度和高度
size = (100,40)
# 背景颜色,默认为白色 RGB(Re,Green,Blue)
bgcolor = (0,0,0)
# 随机字体颜色
random.seed(int(time.time()))
fontcolor = (random.randint(200,255),random.randint(100,255),random.randint(100,255))
# 验证码字体大小
fontsize = 20
# 随机干扰线颜色。
linecolor = (random.randint(0,250),random.randint(0,255),random.randint(0,250))
# 是否要加入干扰线
draw_line = True
# 是否绘制干扰点
draw_point = True
# 加入干扰线的条数
line_number = 3 # abcedf....ABCDEFG...Z
SOURCE = list(string.ascii_letters)
for index in range(0, 10):
SOURCE.append(str(index)) # 用来随机生成一个字符串(包括英文和数字)
# 定义成类方法,然后是私有的,对象在外面不能直接调用
@classmethod
def gene_text(cls):
return ''.join(random.sample(cls.SOURCE,cls.number))#number是生成验证码的位数 # 用来绘制干扰线
@classmethod
def __gene_line(cls,draw,width,height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill = cls.linecolor) # 用来绘制干扰点
@classmethod
def __gene_points(cls,draw,point_chance,width,height):
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
for w in range(width):
for h in range(height):
tmp = random.randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0)) # 生成验证码
@classmethod
def gene_code(cls):
width,height = cls.size #宽和高
image = Image.new('RGBA',(width,height),cls.bgcolor) #创建图片
font = ImageFont.truetype(cls.font_path,cls.fontsize) #验证码的字体
draw = ImageDraw.Draw(image) #创建画笔
text = cls.gene_text() #生成字符串
font_width, font_height = font.getsize(text)
draw.text(((width - font_width) / 2, (height - font_height) / 2),text,font= font,fill=cls.fontcolor) #填充字符串
# 如果需要绘制干扰线
if cls.draw_line:
# 遍历line_number次,就是画line_number根线条
for x in range(0,cls.line_number):
cls.__gene_line(draw,width,height)
# 如果需要绘制噪点
if cls.draw_point:
cls.__gene_points(draw,10,width,height) return (text,image) # text验证码内容, image图片
得到的image不能直接传给前端,需要通过from io import BytesIO处理
def img_catpcha(request):
""" 调用catpcha生成方法生成随机验证码,将验证码写入字节流io.BytesTO,再读取出来。HttpResponse对象才能识别 """
text, image = hycaptcha.Captcha.gene_code()
# print(text)
out = BytesIO()
image.save(out, 'png') # 1.将image储存进BytesIO对象
out.seek(0) # 将光标制定到初始位置(读写的时候都会移动光标)
response = HttpResponse(content_type="image/png") # 申明对象类型
response.write(out.read()) # 2.将储存的image read出来并写入HttpResponse对象中,就可以使用HttpResponse对象将image传给前端页面
response['Content-length'] = out.tell() # 获取image的长度
return response

catpcha的更多相关文章

  1. PHP编写的图片验证码类文件分享方法

    适用于自定义的验证码类! <?php/* * To change this license header, choose License Headers in Project Propertie ...

  2. js canvas captcha

    js canvas captcha https://thejackalofjavascript.com/building-a-captcha-using-html5-canvas/ https://a ...

  3. 使用Python破解验证码

    Keywords: python captcha Most people don’t know this but my honours thesis was about using a compute ...

随机推荐

  1. linux平台模拟生成CAN设备

    前言 使用socketCan的过程中有时候没有can接口设备,但是需要测试一下can接口程序是否有问题, 此时需要系统模拟生成can设备,本文介绍linux平台模拟生成CAN设备的方法. 实现步骤 1 ...

  2. PHP webservice初探

    背景:在最近的开发中,为了解决公司内部系统与外部系统的对接,开始接触到了webservice接口,外部公司提供接口供我们调用,已达到数据同步的目的,因此有必要普及一下web service的知识了! ...

  3. C#浮点数保留位数

    C#浮点数保留位数 这里用String.Forma("{0:F}",x);来解决. 下面是试验和截图 using System; using System.Collections. ...

  4. 用zcat查看压缩日志中百度抓取的量

    比如查看124.251.44.85这一台服务器的07-13,07-14,07-15的日志中百度抓取http://www.baidu.com/search/spider.html 的量 wc命令参考博客 ...

  5. Cocos2d-X数据、动作、消息的基本操作

    加入类的create方法: CREATE_FUNC(ClassName) 使用这个宏能够为类加入一个create方法. 创建类的对象时一律用Class::create()的形式. 在CREATE_FU ...

  6. 监控Linux的Steps&Q&A

    spolight的下载地址:https://www.quest.com/spotlight-on-windows/ 问题1.sar -u 之后,只有一条记录.这种情况执行一下:sudo sar -d; ...

  7. 针对 FastAdmin 2018-01-19 号的升级 SQL (废)

    FastAdmin 在 2018-01-19 升级增加了以下功能. 新增前台会员模块和API会员模块 新增后台会员管理.会员规则和会员分组管理 新增短信发送的行为事件 新增前台Token.短信.日志模 ...

  8. java 多线程之 interrupt()和线程终止方式

    interrupt() 说明 interrupt()的作用是中断本线程. 本线程中断自己是被允许的:其它线程调用本线程的interrupt()方法时,会通过checkAccess()检查权限.这有可能 ...

  9. js搞定网页的简繁转换

    对网页进行简繁字体转换的方法一般有两种:一是使用<简繁通>这样的专业软件,另外一种是制作两套版本的网页.显然,这两种方法都较为麻烦,而且专业软件一般不能用于免费的空间.笔者在这里给大家提供 ...

  10. BaseAction编写:免去一些重复的代码,比如继承ActionSupport和实现ModelDriven接口

    1.BaseAction package com.learning.crm.base; import java.lang.reflect.ParameterizedType; import java. ...