from PIL import Image, ImageDraw, ImageFont, ImageColor
import random
DEFAULT_FONT_PATH = 'c:\windows\fonts\arial.ttf'
def generate_verify_code(len, width, height,font_path=None, font_size=32, bg_color=None,
disturb_lines=20, disturb_points = 1000,
rotation=(-60, 60)):
# 指定字体路径
font_path = font_path or DEFAULT_FONT_PATH
##初始化字体
font_obj = ImageFont.FreeTypeFont(font_path, font_size)
words = '0123456789abcdefghijklmnopqrstuvwxyz'
# 默认图片大小
img_size = (width, height)
##随机字符
def _rand_word():
return random.choice(words)
##填充文字颜色
def _rand_color():
return tuple(random.randint(64, 254) for _ in range(0, 3))
# 背景色
bg_color = bg_color or _rand_color()
# 旋转随机角度default-60 -> 60]
def _rand_rotation():
return random.randint(*rotation)
##生成文字
_words_obj = []
#返回验证码
_words_code = []
for _ in range(len):
##背景透明
_img = Image.new('RGBA', (int(font_size * 0.75), font_size + 2))
## 初始化画笔
_draw = ImageDraw.Draw(_img)
## 写字
tmp = _rand_word()
_words_code.append(tmp)
_draw.text((0 + 2,0), tmp, _rand_color(), font=font_obj)
#释放画笔
del _draw
#旋转角度
_rotated = _img.rotate(_rand_rotation())
_words_obj.append(_rotated)
#创建验证码
img_code = Image.new('RGB', img_size, bg_color)
#添加随机噪点
_draw = ImageDraw.Draw(img_code)
for _ in range(disturb_points):
x = random.randint(0, img_code.width)
y = random.randint(0, img_code.height)
_draw.point((x, y), fill=_rand_color())
# 添加干扰线
lines = [(random.randint(0, img_code.width),
random.randint(0, img_code.height),
random.randint(0, img_code.width),
random.randint(0, img_code.height)
) for _ in range(disturb_lines)]
for line in lines:
_draw.line(line, fill=_rand_color())
del _draw
#初始位置
_x = 10
_y = 0
offset = 10
for word in _words_obj:
#控制打印文字位置
_w = _x + word.width
_h = _y + word.height
img_code.paste(word, (_x, _y, _w, _h), word.convert('RGBA'))
_x = _x + word.width + offset
print(_words_code)
img_code.save(r'C:UserslDesktopcode.png')
generate_verify_code(4, 140, 40, bg_color=(40, 67, 135), disturb_lines=10, disturb_points=200,
rotation=(-30, 30))