from captcha.image import ImageCaptcha
from random import randint
from base64 import b64encode
from base64 import b64decode
from io import BytesIO
import random
from django.http import HttpResponse
# 随机颜色
def get_random_color():
R = random.randrange (0,255,1)
G = random.randrange (0,255,1)
B = random.randrange (0,255,1)
return (R, G, B)
# 生成图片验证码
def VCode(request,length=4, randcolor=get_random_color(),
# length: 验证码长度
# randcolor: 随机颜色
# words: 字符集
# noisecurve_number: 干扰线数量
# noisedot_width: 噪点尺寸
# noisedot_number: 噪点数量
# 返回值:
# key: 验证码字符串
# b64encode: 将验证码转换为base64
# 字典:去除了易混淆的O和l
words="0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ",
noisecurve_number=1, noisedot_width=6, noisedot_number=20):
# 字符集
n, key = len (words), ""
generator = ImageCaptcha (width=120, height=70)
for i in range (length):
key += words[randint(0, n - 1)]
img = generator.create_captcha_image (key, randcolor, get_random_color())
for i in range (noisecurve_number):
img = generator.create_noise_curve (img, randcolor)
img = generator.create_noise_dots (img, randcolor, noisedot_width, noisedot_number)
file = BytesIO ( )
# 将图像保存在内存中
img.save (file, format='png')
# 使用BytesIO().getvalue()转换为字节流
bytes = file.getvalue ( )
# return key, b64encode (bytes)
print (key)
if not request.session.session_key:
request.session.create ( )
session_id = request.session.session_key
request.session['code'] = key
return HttpResponse (b64encode (bytes))
使用captcha库生成验证码
最新推荐文章于 2024-05-16 09:41:01 发布