89 lines
2.6 KiB
Python
89 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""测试验证码生成功能"""
|
|
|
|
try:
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
import random
|
|
import io
|
|
import base64
|
|
|
|
print("✓ Pillow 库已安装")
|
|
|
|
# 生成4位随机数字
|
|
code = ''.join([str(random.randint(0, 9)) for _ in range(4)])
|
|
print(f"✓ 生成验证码: {code}")
|
|
|
|
# 创建图片
|
|
width, height = 120, 40
|
|
image = Image.new('RGB', (width, height), color='#f0f4f8')
|
|
draw = ImageDraw.Draw(image)
|
|
print("✓ 创建图片成功")
|
|
|
|
# 尝试使用系统字体
|
|
font = None
|
|
font_paths = [
|
|
'/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
|
|
'/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf',
|
|
'/System/Library/Fonts/Helvetica.ttc',
|
|
'C:\\Windows\\Fonts\\arial.ttf'
|
|
]
|
|
|
|
for font_path in font_paths:
|
|
try:
|
|
font = ImageFont.truetype(font_path, 28)
|
|
print(f"✓ 使用字体: {font_path}")
|
|
break
|
|
except:
|
|
continue
|
|
|
|
if not font:
|
|
font = ImageFont.load_default()
|
|
print("⚠ 使用默认字体")
|
|
|
|
# 绘制干扰线
|
|
for _ in range(3):
|
|
x1 = random.randint(0, width)
|
|
y1 = random.randint(0, height)
|
|
x2 = random.randint(0, width)
|
|
y2 = random.randint(0, height)
|
|
draw.line([(x1, y1), (x2, y2)], fill='#cbd5e1', width=1)
|
|
|
|
# 绘制验证码文字
|
|
colors = ['#3b82f6', '#2563eb', '#1e40af', '#1e3a8a']
|
|
for i, char in enumerate(code):
|
|
x = 20 + i * 25 + random.randint(-3, 3)
|
|
y = 5 + random.randint(-3, 3)
|
|
color = random.choice(colors)
|
|
draw.text((x, y), char, font=font, fill=color)
|
|
|
|
# 绘制干扰点
|
|
for _ in range(50):
|
|
x = random.randint(0, width)
|
|
y = random.randint(0, height)
|
|
draw.point((x, y), fill='#94a3b8')
|
|
|
|
print("✓ 绘制验证码成功")
|
|
|
|
# 转换为base64
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format='PNG')
|
|
buffer.seek(0)
|
|
img_base64 = base64.b64encode(buffer.getvalue()).decode()
|
|
|
|
print(f"✓ 转换为base64成功 (长度: {len(img_base64)})")
|
|
print("\n验证码功能测试通过!")
|
|
|
|
# 保存测试图片
|
|
image.save('test_captcha.png')
|
|
print("✓ 测试图片已保存为 test_captcha.png")
|
|
|
|
except ImportError as e:
|
|
print(f"✗ 缺少依赖库: {e}")
|
|
print("\n请安装 Pillow 库:")
|
|
print(" pip install Pillow")
|
|
except Exception as e:
|
|
print(f"✗ 测试失败: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|