def verifycode(request):#引入绘图模块from PIL import Image, ImageDraw, ImageFont#引入随机函数模块import random#定义变量,用于画面的背景色、宽、高bgcolor = (random.randrange(20, 100), random.randrange(20, 100), random.randrange(20, 100))width = 100height = 50#创建画面对象im = Image.new('RGB', (width, height), bgcolor)#创建画笔对象draw = ImageDraw.Draw(im)#调用画笔的point()函数绘制噪点for i in range(0, 100):xy = (random.randrange(0, width), random.randrange(0, height))fill = (random.randrange(0, 255), 255, random.randrange(0, 255))draw.point(xy, fill=fill)#定义验证码的备选值str = '1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'#随机选取4个值作为验证码rand_str = ''for i in range(0, 4):rand_str += str[random.randrange(0, len(str))]#构造字体对象font = ImageFont.truetype(r'C:\Windows\Fonts\AdobeArabic-Bold.otf', 40)#构造字体颜色fontcolor1 = (255, random.randrange(0, 255), random.randrange(0, 255))fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255))fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255))fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, 255))#绘制4个字draw.text((5, 2), rand_str[0], font=font, fill=fontcolor1)draw.text((25, 2), rand_str[1], font=font, fill=fontcolor2)draw.text((50, 2), rand_str[2], font=font, fill=fontcolor3)draw.text((75, 2), rand_str[3], font=font, fill=fontcolor4)#释放画笔del draw#存入session,用于做进一步验证# request.session['verifycode'] = rand_str#内存文件操作import iobuf = io.BytesIO()#将图片保存在内存中,文件类型为pngim.save(buf, 'png')#将内存中的图片数据返回给客户端,MIME类型为图片pngreturn HttpResponse(buf.getvalue(), 'image/png')
-
图为示例: