python-captcha-生成图片验证码
import base64
import os
import random
import string
from pathlib import Path
import yaml
from captcha.image import ImageCaptcha
characters = string.digits + string.ascii_uppercase
width, height, n_len, n_class = 170, 80, 4, len(characters)
BASE_DIR = Path(__file__).resolve().parent
png_dir = os.path.join(BASE_DIR, "verify_png")
if not os.path.exists(png_dir):
os.makedirs(png_dir)
yaml_file = "xxx.yaml"
for i in range(1000):
generator = ImageCaptcha(width=width, height=height)
random_str = ''.join([random.choice(characters) for j in range(4)])
img = generator.generate_image(random_str)
ciphertext = base64.urlsafe_b64encode(random_str.encode()).decode()
file_name = png_dir + "\\" + ciphertext + '.jpg'
if not os.path.exists(file_name):
img.save(file_name)
data = {ciphertext: random_str}
with open(yaml_file , 'a+', encoding='utf-8') as f:
yaml.dump(data, stream=f, allow_unicode=True)
with open(yaml_file , 'r', encoding='utf8') as f:
data = yaml.load(f, Loader=yaml.Loader)
print(data)
结果
yaml_files
UFBEMw==: PPD3
QTBQMQ==: A0P1
UDNXRw==: P3WG
OVpJWQ==: 9ZIY
WTBNUg==: Y0MR
N1RTQQ==: 7TSA
U0lFSQ==: SIEI
QTEyRw==: A12G
R1MxTw==: GS1O
MkU3Qg==: 2E7B
N1NNUQ==: 7SMQ
图片
总结
为什么需要生成yaml文件,因为我这是需要用于校验当前图片验证码的准确性,所以使用yaml存储了当前图片的名称和对应的图片内容,读取简单,操作方便.