首先安装Pillow这个包,pip install Pillow==3.4.1
1.生成验证码的流程
1.画面:画面板对象
2.画笔:画笔对象
3.画噪点和干扰线
4.画验证码:备选值,字体,颜色,大小
5.释放画笔
6.将生成的验证码放到session中
7.将图片保存到内存中
8.将内存中的图片数据放回给客户端
2.效果图
-----------------------------------------------------------------------------------------
3.views.py代码
from django.shortcuts import render from PIL import Image, ImageDraw, ImageFont from django.http import HttpResponse import random def verify_code(request): # 1.创建画面对象 # 定义变量,用于画面的背景色、宽、高 bgcolor = (255,255,255) width = 200 height = 45 im = Image.new('RGB', (width, height), bgcolor) # 2.创建画笔对象 draw = ImageDraw.Draw(im) # 3.调用画笔的point()函数绘制噪点 for i in range(0, 100): xy = (random.randrange(0, width), random.randrange(0, height)) fill = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) draw.point(xy, fill=fill) # 调用画笔的point()函数绘制6条干扰线 for i in range(6): x1 = int(random.randrange(0, width)) y1 = int(random.randrange(0, height)) x2 = int(random.randrange(0, width)) y2 = int(random.randrange(0, height)) fill = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) draw.line([(x1, y1), (x2, y2)], fill=fill, width=2) # 4.定义验证码的备选值 str1 = 'ABCD123EFGHIJK456klmnopqrstuvwsyzLMNOPQRS789TUVWXYZ0abcdefghij' # 随机选取4个值作为验证码 rand_str = '' for i in range(0, 4): rand_str += str1[random.randrange(0, len(str1))] # 构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont” # 构造字体类型和大小 font = ImageFont.truetype('FreeMono.ttf', random.randrange(23,40)) # 绘制4个字 draw.text((15, 10), rand_str[0], font=font, fill=random.randrange(0, 255)) draw.text((65, 10), rand_str[1], font=font, fill=random.randrange(0, 255)) draw.text((120, 10), rand_str[2], font=font, fill=random.randrange(0, 255)) draw.text((175, 10), rand_str[3], font=font, fill=random.randrange(0, 255)) # 5.释放画笔 del draw # 6.存入session,用于做进一步验证 # request.session['verifycode'] = rand_str # 内存文件操作(python2) # import cStringIO # buf = cStringIO.StringIO() # 内存文件操作(python3) from io import BytesIO buf = BytesIO() # 7.将图片保存在内存中,文件类型为png im.save(buf, 'png') # 8.将内存中的图片数据返回给客户端,MIME类型为图片png return HttpResponse(buf.getvalue(), 'image/png')
4.urls.代码
from django.conf.urls import url from django.contrib import admin from booktest import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^verify_code/', views.verify_code), ]
5.测试