python中使用PIL制作并验证图片验证码

作者:Geekrun 时间:2023-06-05 11:28:33 

验证码制作


#string模块自带数字、字母、特殊字符变量集合,不需要我们手写集合
import string
import random
import os
import uuid

import settings
from PIL import Image, ImageDraw, ImageColor, ImageFilter, ImageFont

class Code(object):
# 生成随机生成数字或字母
def random_hexdigits(self, len=1):
return random.sample(string.hexdigits, len)

# 生成干扰字符
def punctuation(self, len=1):
return tuple(random.sample(string.punctuation, len))

# 定义干扰字符颜色
def random_color(self, min=64, max=255):
return tuple((random.randint(min, max) for i in range(3)))

# 生成验证码
def creat_code(self, width=80, height=24, color=(192, 192, 192)):
image = Image.new('RGB', (width, height), color)
#建议下载几款字体,变换下风格,我在setting粒定义了static路径,这里就直接导入了
font = ImageFont.truetype(os.path.join(settings.STATICPATH, 'fonts/Lora-Regular.ttf'), 20)
draw = ImageDraw.Draw(image)
self.fill_color(draw, image, 5)
self.fill_dischar(draw, image, 10)
code = self.fill_char(draw, image, 4, 10, font)
image_name = '{}.jpeg'.format(uuid.uuid4().hex)
image_path = os.path.join(settings.STATICPATH, 'code/{}'.format(image_name))
print(image_path)
image.save(image_path)
return {'code': code, 'image_path': image_path}

# 填充颜色
def fill_color(self, draw, image, interval):
for i in range(0, image.width, interval):
 for j in range(0, image.height, interval):
 draw.point((i, j), fill=self.random_color())

# 填充验证码
def fill_dischar(self, draw, image, interval):
for i in range(0, image.width, interval):
 dis = self.punctuation()
 j = random.randrange(3, image.height - 3)
 draw.text((i, j), dis[0], fill=self.random_color(64, 255))

# 填充验证码
def fill_char(self, draw, image, num, interval, font):
code = ''
for i in range(num):
 cha = self.random_hexdigits()
 code += str(cha[0])
 j = random.randrange(0, 5)
 # print(cha)
 # print(image.width*(i/num)+interval,j)
 draw.text((image.width * (i / num) + interval, j), cha[0], fill=self.random_color(32, 127), font=font)
return code

if __name__ == "__main__":
code = Code()
print(code.creat_code())

flask路由配置


import os
from flask import Flask, Response
from flask import render_template
from utils.code import Code

app = Flask(__name__)

@app.route('/')
def Register():
return render_template('verify.html')

@app.route('/codes/')
def code():
infor = Code().creat_code()
image_path = infor["image_path"]
code = infor['code']

print(image_path)
with open(image_path, 'rb') as f:
 image_content = f.read()
os.remove(image_path)
return Response(image_content, mimetype='jpeg')

if __name__ == '__main__':
app.run(debug=True)

前端配置


<div class='form-row'>
  <form id="email_register_form" method="post" autocomplete="off">
   <div class="form-group ">
    <label>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</label>
    <input type="text" id="id_email" name="email" value="None" placeholder="请输入您的邮箱地址"/>
   </div>
   <div class="form-group ">
    <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label>
    <input type="password" id="id_password" name="password" value="None" placeholder="请输入6-20位非中文字符密码"/>
   </div>
   <div class="form-group captcha1 ">
    <label>验&nbsp;证&nbsp;码</label>
    <img src="/codes/" alt="captcha" title="点击切换" class="captcha"
      onclick="this.src='codes/?'+Math.random()"/>
    <input autocomplete="off" id="id_captcha_1" name="captcha_1" height="30px" type="text">
   </div>
   <input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="注册"/>
  </form>

源码分享:https://github.com/geekdick/pythonDemo/tree/master/verify

来源:https://segmentfault.com/a/1190000013739881

标签:python,PIL,验证码
0
投稿

猜你喜欢

  • 有趣的python小程序分享

    2023-11-27 20:31:55
  • jupyter notebook保存文件默认路径更改方法汇总(亲测可以)

    2023-01-12 09:05:07
  • MySQL skip-character-set-client-handshake导致的一个字符集问题

    2024-01-15 11:33:26
  • 永久解决VSCode终端中文乱码问题

    2023-09-18 14:47:57
  • 解决PyCharm 中写 Turtle代码没提示以及标黄的问题

    2023-05-12 09:08:30
  • Python利用fastapi实现上传文件

    2023-12-09 05:54:40
  • Django+Ajax+jQuery实现网页动态更新的实例

    2023-02-11 03:23:19
  • Oracle外键不加索引引起死锁示例

    2024-01-20 20:10:08
  • Python基础之字符串操作常用函数集合

    2023-11-26 23:26:12
  • Python 带星号(* 或 **)的函数参数详解

    2023-04-25 22:36:40
  • 一些CSS样式书写技巧

    2007-10-16 12:57:00
  • mysql主从同步复制错误解决一例

    2024-01-13 17:21:54
  • python+mysql实现个人论文管理系统

    2024-01-25 02:00:25
  • ASP XML制作菜单管理程序

    2011-04-04 11:15:00
  • golang Gorm与数据库完整性约束详解

    2024-01-13 03:34:01
  • Python利用Selenium实现弹出框的处理

    2021-11-12 23:21:50
  • numpy自动生成数组详解

    2023-09-02 22:53:47
  • Go微服务项目配置文件的定义和读取示例详解

    2023-06-23 22:48:50
  • 实操MySQL+PostgreSQL批量插入更新insertOrUpdate

    2024-01-17 09:06:19
  • 基于Python socket实现简易网络聊天室

    2021-10-19 09:10:30
  • asp之家 网络编程 m.aspxhome.com