網站首頁 編程語言 正文
背景
在注冊或者登陸場景下,經常會遇到需要輸入圖片驗證碼的情況,最經典的就是12306買火車票。圖片驗證碼的破解還是有一定難度的,而且如果配合上時間和次數的驗證,可以很大程度上防止模擬登陸或者暴力破解,保護用戶信息,同時很大程度上減少對服務器的惡意請求。今天我們就用python的django框架+PIL實現簡單的圖片驗證碼。
環境
python:3.6.5
django:3.1.6
pillow:5.2.0
【說明】:需要有django基礎,比如路由、視圖函數和啟動命令等。
代碼
check_code.py文件:
功能:
- 生成4位的隨機字符串,并且將隨機字符串寫到圖片上;
- 將隨機字符串和圖片格式的字符串作為返回值。
# -*- coding:utf-8 -*-
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
# 小寫字母,去除可能會造成干擾的i,l,o,z
_letter_cases = "abcdefghjkmnpqrstuvwxy"
# 大寫字母
_upper_cases = _letter_cases.upper()
# 數字
_numbers = ''.join(map(str, range(3, 10)))
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
def create_validate_code(
? ? ? ? size=(120, 30),
? ? ? ? chars=init_chars,
? ? ? ? img_type='GIF',
? ? ? ? mode='RGB',
? ? ? ? bg_color=(255, 255, 255),
? ? ? ? fg_color=(0, 0, 255),
? ? ? ? font_size=18,
? ? ? ? font_type="Monaco.ttf",
? ? ? ? length=4,
? ? ? ? draw_lines=True,
? ? ? ? n_line=(1, 2),
? ? ? ? draw_points=True,
? ? ? ? point_chance=2):
? ? """
? ? @todo: 生成驗證碼圖片
? ? @param size: 圖片的大小,格式(寬,高),默認為(120, 30)
? ? @param chars: 允許的字符集合,格式字符串
? ? @param img_type: 圖片保存的格式,默認為GIF,可選的為GIF,JPEG,TIFF,PNG
? ? @param mode: 圖片模式,默認為RGB
? ? @param bg_color: 背景顏色,默認為白色
? ? @param fg_color: 前景色,驗證碼字符顏色,默認為藍色#0000FF
? ? @param font_size: 驗證碼字體大小
? ? @param font_type: 驗證碼字體,默認為 ae_AlArabiya.ttf
? ? @param length: 驗證碼字符個數
? ? @param draw_lines: 是否劃干擾線
? ? @param n_lines: 干擾線的條數范圍,格式元組,默認為(1, 2),只有draw_lines為True時有效
? ? @param draw_points: 是否畫干擾點
? ? @param point_chance: 干擾點出現的概率,大小范圍[0, 100]
? ? @return: [0]: PIL Image實例
? ? @return: [1]: 驗證碼圖片中的字符串
? ? """
? ? # 寬和高
? ? width, height = size
? ? # 創建圖形
? ? img = Image.new(mode, size, bg_color)
? ? # 創建畫筆
? ? draw = ImageDraw.Draw(img)
? ? def get_chars():
? ? ? ? """生成指定長度的字符串,返回列表格式"""
? ? ? ? return random.sample(chars, length)
? ? def create_line():
? ? ? ? """繪制干擾線條"""
? ? ? ? # 干擾線條數
? ? ? ? line_num = random.randint(*n_line)
? ? ? ? for i in range(line_num):
? ? ? ? ? ? # 起始點
? ? ? ? ? ? begin = (random.randint(0, size[0]), random.randint(0, size[1]))
? ? ? ? ? ? # 結束點
? ? ? ? ? ? end = (random.randint(0, size[0]), random.randint(0, size[1]))
? ? ? ? ? ? draw.line([begin, end], fill=(0, 0, 0))
? ? def create_points():
? ? ? ? """繪制干擾點"""
? ? ? ? # 大小限制在[0, 100]
? ? ? ? chance = min(100, max(0, int(point_chance)))
? ? ? ? for w in range(width):
? ? ? ? ? ? for h in range(height):
? ? ? ? ? ? ? ? tmp = random.randint(0, 100)
? ? ? ? ? ? ? ? if tmp > 100 - chance:
? ? ? ? ? ? ? ? ? ? draw.point((w, h), fill=(0, 0, 0))
? ? def create_strs():
? ? ? ? """繪制驗證碼字符"""
? ? ? ? c_chars = get_chars()
? ? ? ? # 每個字符前后以空格隔開
? ? ? ? strs = ' %s ' % ' '.join(c_chars)
? ? ? ? font = ImageFont.truetype(font_type, font_size)
? ? ? ? font_width, font_height = font.getsize(strs)
? ? ? ? draw.text(((width - font_width) / 3, (height - font_height) / 3),
? ? ? ? ? ? ? ? ? strs, font=font, fill=fg_color)
? ? ? ? return ''.join(c_chars)
? ? if draw_lines:
? ? ? ? create_line()
? ? if draw_points:
? ? ? ? create_points()
? ? strs = create_strs()
? ? # 圖形扭曲參數
? ? params = [1 - float(random.randint(1, 2)) / 100,
? ? ? ? ? ? ? 0,
? ? ? ? ? ? ? 0,
? ? ? ? ? ? ? 0,
? ? ? ? ? ? ? 1 - float(random.randint(1, 10)) / 100,
? ? ? ? ? ? ? float(random.randint(1, 2)) / 500,
? ? ? ? ? ? ? 0.001,
? ? ? ? ? ? ? float(random.randint(1, 2)) / 500
? ? ? ? ? ? ? ]
? ? # 創建扭曲
? ? img = img.transform(size, Image.PERSPECTIVE, params)
? ? # 濾鏡,邊界加強(閾值更大)
? ? img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
? ? return img, strs
路由:
from django.urls import path
from web.views import home, account
urlpatterns = [
? ? path('code/', home.code),
? ? path('test/', home.test),
]
視圖函數:
# encoding=utf-8
import json
import io
from django.shortcuts import render, HttpResponse, redirect
import check_code as CheckCode
def code(req):
? ? """
? ? 獲取驗證碼
? ? :param req:
? ? :return:
? ? """
? ? stream = io.BytesIO()
? ? # 創建隨機字符串code
? ? # 創建一張圖片格式的字符串,將隨機字符串寫到圖片上
? ? img, code = CheckCode.create_validate_code()
? ? print('[check_code][code]:', code)
? ? # 保存到內存中
? ? img.save(stream, 'PNG')
? ? req.session['CheckCode'] = code
? ? return HttpResponse(stream.getvalue())
def test(req):
? ? """通過請求頭獲取用戶設備信息"""
? ? print(type(req))
? ? return render(req, 'test.html')
html文件:
功能:
- 給圖片綁定onclick事件,這樣每點擊一次就重新生成一個驗證碼;
- img標簽的src屬性可以是字節流形式的圖片,每次請求check_code視圖函數,瀏覽器會將返回的圖片字符串解析為圖片作為src屬性。
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <title>test</title>
</head>
<body>
? ? <h1>圖片驗證碼</h1>
? ? <img src="/check_code/" alt="驗證碼" onclick="ChangeCode(this);">
? ? <script>
? ? ? ? function ChangeCode(ths) {
? ? ? ? ? ? ths.src += '?';
? ? ? ? }
? ? </script>
</body>
</html>
結果
啟動django項目,瀏覽器訪問http://127.0.0.1:8000/test/,可以看到圖片驗證碼:
原文鏈接:https://blog.csdn.net/kongsuhongbaby/article/details/119083806
相關推薦
- 2022-12-24 python使用turtle庫寫六角形的思路與代碼_python
- 2022-02-02 【layui】【laydate】設置可以選擇相同的年份范圍
- 2022-09-15 Python基本結構之判斷語句的用法詳解_python
- 2022-11-06 react中關于Context/Provider/Consumer傳參的使用_React
- 2022-12-05 Python實現字符串模糊匹配方式_python
- 2022-10-24 Golang設計模式工廠模式實戰寫法示例詳解_Golang
- 2022-09-05 Spring是如何解決循環依賴的?
- 2022-06-15 go語言數組及結構體繼承和初始化示例解析_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支