• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python生成图片验证码的代码

python 水墨上仙 1967次浏览

下面的代码是使用python生成图片验证码,然后结合flask,返回给前端显示。font_type指定字体路径,这里使用Mac原版字体Monaco.tar,运行程序,打开浏览器访问:localhost:18888/code/
转自:http://codingnow.cn/python/627.html
作者:Alex Zhou

#!/usr/bin/env python  
#coding=utf-8  
 
import random  
import Image, ImageDraw, ImageFont, ImageFilter  
import StringIO
 
from flask import Flask
 
#map:将str函数作用于后面序列的每一个元素
numbers = ''.join(map(str, range(10))) 
chars = ''.join((numbers))  
 
def create_validate_code(size=(120, 30),  
                         chars=chars,  
                         mode="RGB",  
                         bg_color=(255, 255, 255),  
                         fg_color=(255, 0, 0),  
                         font_size=18,  
                         font_type="Monaco.ttf",  
                         length=4,  
                         draw_points=True,  
                         point_chance = 2):  
    ''''' 
    size: 图片的大小,格式(宽,高),默认为(120, 30) 
    chars: 允许的字符集合,格式字符串 
    mode: 图片模式,默认为RGB 
    bg_color: 背景颜色,默认为白色 
    fg_color: 前景色,验证码字符颜色 
    font_size: 验证码字体大小 
    font_type: 验证码字体,默认为 Monaco.ttf 
    length: 验证码字符个数 
    draw_points: 是否画干扰点 
    point_chance: 干扰点出现的概率,大小范围[0, 50] 
    ''' 
 
    width, height = size  
    img = Image.new(mode, size, bg_color) # 创建图形  
    draw = ImageDraw.Draw(img) # 创建画笔  
 
    def get_chars():  
        '''''生成给定长度的字符串,返回列表格式''' 
        return random.sample(chars, length)  
 
    def create_points():  
        '''''绘制干扰点''' 
        chance = min(50, max(0, int(point_chance))) # 大小限制在[0, 50]  
 
        for w in xrange(width):  
            for h in xrange(height):  
                tmp = random.randint(0, 50)  
                if tmp > 50 - chance:  
                    draw.point((w, h), fill=(0, 0, 0))  
 
    def create_strs():  
        '''''绘制验证码字符''' 
        c_chars = get_chars()  
        strs = '%s' % ''.join(c_chars)  
 
        font = ImageFont.truetype(font_type, font_size)  
        font_width, font_height = font.getsize(strs)  
 
        draw.text(((width - font_width) / 3, (height - font_height) / 4),  
                    strs, font=font, fill=fg_color)  
 
        return strs  
 
    if draw_points:  
        create_points()  
    strs = create_strs()  
 
    # 图形扭曲参数  
    params = [1 - float(random.randint(1, 2)) / 100,  
              0,  
              0,  
              0,  
              1 - float(random.randint(1, 10)) / 100,  
              float(random.randint(1, 2)) / 500,  
              0.001,  
              float(random.randint(1, 2)) / 500 
              ]  
    img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲  
 
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)  
 
    return img,strs  
 
app = Flask(__name__)  
 
@app.route('/')  
def index():  
    return 'test' 
 
@app.route('/code/')  
def get_code():  
    #把strs发给前端,或者在后台使用session保存  
    code_img,strs = create_validate_code()  
    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=18888,debug=True)


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python生成图片验证码的代码
喜欢 (0)
加载中……