使用 Pillow (PIL 友好分支) 生成驗證碼圖片:背景、文字繪製、仿射變形扭曲、隨機干擾線/噪點、字體載入、儲存 JPEG/PNG。
pip install Pillow
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import math
from PIL import Image, ImageDraw, ImageFont, ImageFilter
class CaptchaGenerator:
def __init__(self, width=120, height=40, font_size=28, font_path=None):
self.width = width
self.height = height
self.font_size = font_size
self.font = ImageFont.truetype(font_path or self._default_font(), font_size)
self.bg_color = (255, 255, 255)
self.font_color = (0, 0, 0)
self.line_color = (0, 0, 0)
def _default_font(self):
# 跨平台嘗試尋找字體
import os
candidates = [
'/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', # Linux
'C:/Windows/Fonts/arial.ttf', # Windows
'/System/Library/Fonts/Arial.ttf' # macOS
]
for f in candidates:
if os.path.exists(f):
return f
return ImageFont.load_default()
def generate_code(self, length=4, chars='ABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
'''生成隨機驗證碼字串 (排除易混淆字元)'''
return ''.join(random.choices(chars, k=length))
def create_base_image(self, text):
'''建立基礎圖片:背景 + 文字'''
img = Image.new('RGB', (self.width, self.height), self.bg_color)
draw = ImageDraw.Draw(img)
# 計算文字置中位置
bbox = draw.textbbox((0, 0), text, font=self.font)
text_w = bbox[2] - bbox[0]
text_h = bbox[3] - bbox[1]
x = (self.width - text_w) // 2
y = (self.height - text_h) // 2
draw.text((x, y), text, font=self.font, fill=self.font_color)
return img
def distort(self, img):
'''仿射變形扭曲'''
# 參數: (a, b, c, d, e, f) -> x' = ax+by+c, y' = dx+ey+f
# 輕微傾斜 + 扭曲
params = (
1, random.uniform(-0.3, 0.3), 0,
random.uniform(-0.1, 0.1), 1, 0
)
new_w = self.width + 30
new_h = self.height + 10
return img.transform((new_w, new_h), Image.AFFINE, params, Image.BICUBIC)
def add_noise(self, img, line_count=5, point_count=50):
'''添加干擾線與噪點'''
draw = ImageDraw.Draw(img)
w, h = img.size
# 干擾線
for _ in range(line_count):
x1, y1 = random.randint(0, w), random.randint(0, h)
x2, y2 = random.randint(0, w), random.randint(0, h)
draw.line([(x1, y1), (x2, y2)], fill=self.line_color, width=1)
# 噪點
for _ in range(point_count):
x, y = random.randint(0, w), random.randint(0, h)
draw.point((x, y), fill=self.line_color)
return img
def generate(self, code=None):
code = code or self.generate_code()
img = self.create_base_image(code)
img = self.distort(img)
img = self.add_noise(img)
# 可選:濾鏡模糊增加難度
# img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
return code, img
# 使用範例
if __name__ == '__main__':
gen = CaptchaGenerator()
code, img = gen.generate()
img.save(f'captcha_{code}.jpeg', 'JPEG', quality=85)
print(f'Generated: {code}')
| 技巧 | 實現 | 目的 |
|---|---|---|
| 字體載入 | ImageFont.truetype(path, size) | 支援 TTF/OTF,跨平台需處理路徑 |
| 文字置中 | textbbox() 計算寬高 | 精確置中 (Pillow 8.0+) |
| 仿射變形 | img.transform(size, AFFINE, (a,b,c,d,e,f)) | 傾斜、扭曲、縮放組合 |
| 干擾線 | draw.line() 隨機端點 | 破壞 OCR 字符連續性 |
| 噪點 | draw.point() 隨機像素 | 增加背景複雜度 |
| 濾鏡 | ImageFilter (BLUR, EDGE_ENHANCE) | 進一步干擾識別 |
from flask import Flask, session, send_file, io
app = Flask(__name__)
app.secret_key = 'super-secret'
gen = CaptchaGenerator()
@app.route('/captcha')
def captcha():
code, img = gen.generate()
session['captcha_code'] = code.upper()
buf = io.BytesIO()
img.save(buf, 'JPEG')
buf.seek(0)
return send_file(buf, mimetype='image/jpeg')
@app.route('/verify', methods=['POST'])
def verify():
user_input = request.form.get('captcha', '').upper()
if user_input == session.get('captcha_code'):
return 'OK'
return 'Invalid', 400