一.基本流程:
1.首先创建图片对象
2.创建画笔对象
3.往图片中添加噪点
4.生成验证码随机数
5.绘制图片,完成后释放画笔
6.文件操作,并且返回
二.代码块
from PIL import Image,ImageDraw,ImageFont
import random
from django.http import HttpResponse
import io
def virefycode(request):
width = 100
height = 50
bgcolor = (random.randrange(255),random.randrange(255),random.randrange(255)) # 随机颜色生成
image = Image.new('RGB',(width,height),bgcolor) # 创建图片
draw = ImageDraw.Draw(image) # 画笔对象
for i in range(1000):
xy = (random.randint(0,width),random.randint(0,height) # 噪点的范围
fill = (random.randint(0,255),255,random.randint(0,255) # 取随机颜色
draw.point(xy,fill = fill) # 绘制噪点
# 添加验证码
str = '1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'
# 产生随机数
rand_str = ''
for i in range(0,4):
rand_str += str[random.randint(0, len(str)-1)]
# 指定字体类型
font = ImageFont.truetype('static/fonts/Songti.ttc', 35) # 后面的是字体的大小
# 字体颜色
font_color1 = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
font_color2 = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
font_color3 = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
font_color4 = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 绘制字体
draw.text((5, 2), rand_str[0], font=font, fill=font_color1)
draw.text((25, 2), rand_str[1], font=font, fill=font_color2)
draw.text((45, 2), rand_str[2], font=font, fill=font_color3)
draw.text((65, 2), rand_str[3], font=font, fill=font_color4)
# 释放画笔
del draw
# 文件操作
buff = io.BytesIO()
image.save(buff, 'png')
return HttpResponse(buff.getvalue(), 'image/png')