python3 pillow生成验证码图片方法介绍


本文摘自php中文网,作者巴扎黑,侵删。

本篇文章主要介绍了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配置和前端代码未给出。

以上就是python3 pillow生成验证码图片方法介绍的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python什么时候用类方法

Python中预处理以及热图的简单介绍

Python代码块是什么

Python爬虫怎么挣钱

Python读取文本中数据并转化为dataframe的实例_Python

Python入口函数是什么

简述Python如何调用系统底层api播放wav文件

ipad怎么写Python

iPythonPython区别

Python中yaml配置文件模块的使用详解

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...