下面的代碼是使用python生成圖片驗證碼,然後結合flask,返回給前端顯示。font_type指定字體路徑,這裏使用Mac原版字體Monaco.tar,運行程序,打開瀏覽器訪問:localhost:18888/code/
#!/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)
轉載請註明來自:Alex Zhou,本文鏈接:http://codingnow.cn/python/627.html