Created
December 4, 2020 02:48
-
-
Save BroHui/72dc3acc4c296c96e0e9013417c68e93 to your computer and use it in GitHub Desktop.
Python生成验证码方案
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
""" | |
Python 验证码生成封装 | |
生产环境使用NO POLT模式,单次耗时100ms左右。 | |
2020-12-04 | |
""" | |
from captcha.image import ImageCaptcha | |
from PIL import Image | |
import base64 | |
import random | |
number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] | |
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', | |
'v', 'w', 'x', 'y', 'z'] | |
ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', | |
'V', 'W', 'X', 'Y', 'Z'] | |
MISC = number + alphabet + ALPHABET | |
def random_captcha_text(char_set=None, captcha_size=4): | |
if char_set is None: | |
char_set = MISC | |
captcha_text = [] | |
for i in range(captcha_size): | |
c = random.choice(char_set) | |
captcha_text.append(c) | |
return captcha_text | |
def gen_captcha_text_and_image(): | |
""" | |
仅供训练调试使用 | |
:return: | |
验证码答案,验证码np图形 | |
""" | |
image1 = ImageCaptcha() | |
captcha_text = random_captcha_text() | |
captcha_text = ''.join(captcha_text) | |
captcha = image1.generate(captcha_text) | |
captcha_image = Image.open(captcha) | |
captcha_image_np = np.array(captcha_image) | |
return captcha_text, captcha_image_np | |
def gen_captcha_embed_base64(): | |
""" | |
供网页使用 | |
:return: | |
验证码答案,base64编码过得web内嵌png图片 | |
""" | |
image1 = ImageCaptcha() | |
captcha_text = random_captcha_text() | |
captcha_text = ''.join(captcha_text) | |
captcha = image1.generate(captcha_text) | |
data = captcha.getvalue() | |
encode_data = base64.b64encode(data) | |
data = encode_data.encode('utf-8') | |
img_data = "data:image/png;base64,{data}".format(data=data) | |
return captcha_text, img_data | |
if __name__ == '__main__': | |
PLOT = 0 | |
if PLOT: | |
import matplotlib.pyplot as plt | |
import numpy as np | |
# 正确的答案也显示在图片上,可作数据源用TensorFlow训练,获得破解模型。 | |
text, image = gen_captcha_text_and_image() | |
f = plt.figure() | |
ax = f.add_subplot(111) | |
ax.text(0.1, 0.9, text, ha='center', va='center', transform=ax.transAxes) | |
plt.imshow(image) | |
plt.show() | |
else: | |
text, embed_data = gen_captcha_embed_base64() | |
print(text) | |
print(embed_data[:100]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment