使用Flask 生成中文图片验证码
因最近要用到验证码,上网搜了下,发现什么验证码感觉都能被攻破,连最近疯传的变态的12306的验证码居然有人一天就攻破了,所以,综合考虑,还是使用汉字:
web框架是Flask,然后使用python的Image库生成中文验证码,后续也可加入数字字母啥的。
代码如下:
# -*- coding: utf-8 -*-
import sys reload(sys)
sys.setdefaultencoding('utf-8')
"""
__author__="tina"
__mtime__ = '2015/12/19 15:32'
"""
import random
import Image, ImageDraw, ImageFont
import StringIO from flask import Flask class RandomChar():
"""用于随机生成汉字对应的Unicode字符"""
@staticmethod
def Unicode():
val = random.randint(0x4E00, 0x9FBB)
return unichr(val) @staticmethod
def GB2312():
head = random.randint(0xB0, 0xCF)
body = random.randint(0xA, 0xF)
tail = random.randint(0, 0xF)
val = ( head << 8 ) | (body << 4) | tail
str = "%x" % val
#
return str.decode('hex').decode('gb2312','ignore') class ImageChar():
def __init__(self, fontColor = (0, 0, 0),
size = (100, 40),
fontPath = 'STZHONGS.TTF',
bgColor = (255, 255, 255, 255),
fontSize = 20):
self.size = size
self.fontPath = fontPath
self.bgColor = bgColor
self.fontSize = fontSize
self.fontColor = fontColor
self.font = ImageFont.truetype(self.fontPath, self.fontSize)
self.image = Image.new('RGBA', size, bgColor) def rotate(self):
img1 = self.image.rotate(random.randint(-5, 5), expand=0)#默认为0,表示剪裁掉伸到画板外面的部分
img = Image.new('RGBA',img1.size,(255,)*4)
self.image = Image.composite(img1,img,img1) def drawText(self, pos, txt, fill):
draw = ImageDraw.Draw(self.image)
draw.text(pos, txt, font=self.font, fill=fill)
del draw def randRGB(self):
return (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255)) def randPoint(self):
(width, height) = self.size
return (random.randint(0, width), random.randint(0, height)) def randLine(self, num):
draw = ImageDraw.Draw(self.image)
for i in range(0, num):
draw.line([self.randPoint(), self.randPoint()], self.randRGB())
del draw def randChinese(self, num):
gap = 0
start = 0
strRes = ''
for i in range(0, num):
char = RandomChar().GB2312()
strRes += char
x = start + self.fontSize * i + random.randint(0, gap) + gap * i
self.drawText((x, random.randint(-5, 5)), char, (0,0,0))
self.rotate()
print strRes
self.randLine(8)
return strRes,self.image app = Flask(__name__) @app.route('/')
def index():
return 'hello World!' @app.route('/VerifyCode/')
def get_code():
#把strs发给前端,或者在后台使用session保存
ic = ImageChar(fontColor=(100,211, 90))
strs,code_img = ic.randChinese(4)
buf = StringIO.StringIO()
code_img.save(buf,'JPEG',quality=70)
buf_str = buf.getvalue()
response = app.make_response(buf_str)
response.headers['Content-Type'] = 'image/jpeg'
return response if __name__ == "__main__":
app.run(host="localhost",port=5000,debug=True)
然后运行,在浏览器中输入:localhost:5000/VerifyCode 就可看到生成的验证码。
效果图如下:

注:
1.我是用的是windows 下STZHONGS.TTF 这个字体,如果使用,请指定fontPath路径。
使用Flask 生成中文图片验证码的更多相关文章
- springboot搭建项目,实现Java生成随机图片验证码。
这篇文章主要介绍了如何通过Java如何生成验证码并验证.验证码的作用我想必大家都知道,话不多说开始实施! 首先创建一个springboot项目以下是项目结构,内有utli工具类.存放生成图片验证码方法 ...
- python 生成随机图片验证码
1.安装pillow模块 pip install pillow (1)创建图片 from PIL import Image #定义使用Image类实例化一个长为400px,宽为400px,基于RGB的 ...
- Linux服务器 java生成的图片验证码乱码问题
问题:如图所示项目中生成的图形验证码不能正常显示出需要的字体 原因: linux下没有对应的字体 查找项目中使用到系统字体的地方,如下: 解决: 1. 在本地 路径 C:\Windows\Fonts ...
- Java生成随机图片验证码
前台html代码 [Java] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 <div style="margin-top: 50px;&quo ...
- PHP生成登录图片验证码
很久之前写的 感觉登录还挺常用 记录一下. public function makeLoginCodeAction() //生成登录页的验证码 { Header("Content-type: ...
- 生成base64图片验证码
github.com/mojocn/base64Captcha func GetCaptcha(c *gin.Context){ driver := base64Captcha.NewDriverDi ...
- 用C#生成随机中文汉字验证码的基本原理
前几天去申请免费QQ号码,突然发现申请表单中的验证码内容换成了中文,这叫真叫我大跌眼镜感到好笑,Moper上的猫儿们都大骂腾讯采用中文验证码.^_^ 我不得不佩服腾讯为了防止目前网络上横行的QQ号码 ...
- MVC伪一个12306图片验证码
本文的来由主要是满足自己的好奇心,而不是证明什么东西,如果涉及到什么官方性的事情,麻烦通知我谢谢:本篇将要和大家分享的是一个看起来通12306图片验证码相似的效果,这篇应该是今年农历最后一篇分享文章了 ...
- asp.net web api实现图片点击式图片验证码
现在验证码的形式越来越丰富,今天要实现的是在点击图片中的文字来进行校验的验证码,如图 这种验证码验证是验证鼠标是否选中了图片中文字的位置,以及选择的顺序,产生验证码的时候可以提供一组底图,然后随机获取 ...
随机推荐
- 【转】Ubuntu安装ARM架构GCC工具链(ubuntu install ARM toolchain)最简单办法
原文网址:http://www.cnblogs.com/muyun/p/3370996.html 一.安装ARM-Linux-GCC工具链 只需要一句命令: sudo apt-get install ...
- 中国版 Ubuntu Kylin 14.04 LTS 麒麟操作系统中文版发布下载 (Ubuntu天朝定制版)
中国版 Ubuntu Kylin 14.04 LTS 麒麟操作系统中文版发布下载 (Ubuntu天朝定制版) http://www.iplaysoft.com/ubuntukylin.html
- curl 浏览器模拟请求实战
1,curl 常用选项
- Unity position和localposition
1. position是根据世界原点为中心 2. localPosition是根据父节点为中心,如果没有父节点,localpositon和position是没有区别的 3.选中一个物体左上角Globa ...
- Han Move(细节题)
Problem 1609 - Han Move Time Limit: 1000MS Memory Limit: 65536KB Total Submit: 620 Accepted: 1 ...
- ChromiumFX中js调用C#方法
server端代码: ChromiumWebBrowser wb; wb.AddGlobalJSFunction("CfxHelloWorld").Execute += CfxHe ...
- indesign 注意事项
画册 42 * 28.5加出血 42.6 * 29.1用纸 889 * 1194 注意事项:indd文件打印需转曲线 快捷键:ctrl+shift+O ctrl+shift+G (2)应用图片需单独创 ...
- NET基础课--JIT编译器如何工作1
1..Net运行时调用JIT编译器,用来把由C#编译器生成的IL指令编译成机器代码.这一任务在应用程序的运行期间是分步进行的.JIT并不是在程序一开始就编译整个应用程序,取而代之的是,CLR是一个函数 ...
- android一些常用的代码1(收藏)
以下内容来自多个开源项目的整理和自己的项目积累. 1.拨打电话 public static void call(Context context, String phoneNumber) { conte ...
- JS--Div中数据滚动到最后一条重新从头开始滚动
在做东西时要求让数据滚动,且滚动到最后一条时,从头再开始滚动,样图如下: