可直接复制到Django项目中使用
# author:sunshinefrom django.http import HttpResponsefrom PIL import Image, ImageDraw, ImageFont, ImageFilterfrom django.conf import settingsimport randomimport stringimport timeimport io# 字体的位置,不同版本的系统会有不同# font_path = 'C:\\WINDOWS\\Fonts\\SIMYOU.TTF'# 将字体文件放置于static文件内,不依赖于系统font_path = 'static/fonts/Ubuntu-R.ttf'# 设置验证码的位数number = 4# 生成验证码图片的高度和宽度,可以依据实际情况选择size = (90, 38)# 背景颜色,默认为白色bgcolor = (255, 255, 255)# 字体颜色,默认为蓝色fontcolor = (0, 0, 255)# 干扰线颜色。默认为红色linecolor = (255, 0, 0)# 是否要加入干扰线draw_line = True# 加入干扰线条数的上下限line_number = (1, 5)# 获取随机字串作为验证码def gen_text():source = list(string.ascii_letters)for item in range(0, 10):source.append(str(item))# number是生成验证码的位数return ''.join(random.sample(source, number))# 用来绘制干扰线def gene_line(draw, width, height):begin = (random.randint(0, width), random.randint(0, height))end = (random.randint(0, width), random.randint(0, height))draw.line([begin, end], fill=linecolor)# 上传文件展示路径前缀static_base = '/'static_url = settings.MEDIA_URLdef gene_code(request):# save_path = settings.MEDIA_ROOT + "/"# filename = int(time.time())width, height = size # 宽和高# 创建图片image = Image.new('RGBA', (width, height), bgcolor)# 验证码的字体和字体大小font = ImageFont.truetype(font_path, 25)# 创建画笔draw = ImageDraw.Draw(image)# 生成字符串,得到随机数字与字母组合text = gen_text()# 将得到的字符串保存到sessionrequest.session['vk'] = text# 设置5分钟过期request.session.set_expiry(5 * 60)font_width, font_height = font.getsize(text)# 讲字符串写到图片上draw.text(((width - font_width) / number,(height - font_height) / number),text, font=font, fill=fontcolor) # 填充字符串# 调用画笔的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)# 绘制干扰线段if draw_line:gene_line(draw, width, height)gene_line(draw, width, height)gene_line(draw, width, height)gene_line(draw, width, height)image = image.transform((width + 20, height + 10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 创建扭曲# 滤镜,边界加强image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)# 释放画笔del draw# 将图片保存然后返回给用户# image.save('%s%s.png' % (save_path, filename)) # 保存验证码图片# image_data = open(save_path + str(filename) + '.png', "rb").read()# return HttpResponse(image_data, content_type="image/png")# 直接内存文件操作,将图片数据返回,不用担心验证码图片过多buf = io.BytesIO()# 将图片保存在内存中,文件类型为pngimage.save(buf, 'png')# 将内存中的图片数据返回给客户端,MIME类型为图片pngreturn HttpResponse(buf.getvalue(), 'image/png')