脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python3 pillow生成简单验证码图片的示例

python3 pillow生成简单验证码图片的示例

2020-12-08 00:46Shao Python

本篇文章主要介绍了python3 pillow生成简单验证码图片的示例,非常具有实用价值,需要的朋友可以参考下

使用Python的pillow模块 random 模块随机生成验证码图片,并应用到Django项目中

安装pillow

?
1
$ pip3 install pillow

生成验证码图片

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
\vericode.py
 
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
 
 #随机码 默认长度=1
def random_code(lenght=1): 
  code = ''
  for char in range(lenght):
    code += chr(random.randint(65,90))
  return code
 
 #随机颜色 默认颜色范围【1,255】
def random_color(s=1,e=255):
  return (random.randint(s,e),random.randint(s,e),random.randint(s,e))
 
 #生成验证码图片
 #length 验证码长度
 #width 图片宽度
 #height 图片高度
 #返回验证码和图片
def veri_code(lenght=4,width=160,height=40):
  #创建Image对象
  image = Image.new('RGB',(width,height),(255,255,255))
  #创建Font对象
  font = ImageFont.truetype('Arial.ttf',32)
  #创建Draw对象
  draw = ImageDraw.Draw(image)
  #随机颜色填充每个像素
  for x in range(width):
    for y in range(height):
      draw.point((x,y),fill=random_color(64,255))
  #验证码
  code = random_code(lenght)
  #随机颜色验证码写到图片上
  for t in range(lenght):
    draw.text((40*t+5,5),code[t],font=font,fill=random_color(32,127))
  #模糊滤镜
  image = image.filter(ImageFilter.BLUR)
  return code,image

应用

编写Django应用下的视图函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
\views.py
 
from . import vericode.py
from io import BytesIO
from django.http import HttpResponse
 
def verify_code(request):
  f = BytesIO()
  code,image = vericode.veri_code()
  image.save(f,'jpeg')
  request.session['vericode'] = code
  return HttpResponse(f.getvalue())
 
def submit_xxx(request):
  if request.method == "POST":
    vericode = request.session.get("vericode").upper()
    submitcode = request.POST.get("vericode").upper()
    if submitcode == vericode:
      return HttpResponse('ok')
  return HttpResponse('error')

这里使用了Django的session,需要在Django settings.py的INSTALLED_APPS中添加'django.contrib.sessions'(默认添加)
verify_code视图函数将验证码添加到session中和验证码图片一起发送给浏览器,当提交表单到submit_xxx()时,先从session中获取验证码,再对比从表单中的输入的验证码。

这里只是简单说明,url配置和前端代码未给出。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000011228983

延伸 · 阅读

精彩推荐