Python生成随机图形验证码
时间: 2024-06-14 21:02:21 浏览: 104
python生成图形验证码
在Python中,生成随机图形验证码通常涉及到图像处理库,如PIL(Python Imaging Library)或其更新版本Pillow,以及可能用到的随机数生成库如random和numpy。以下是一个简单的步骤概述:
1. 导入所需的库:
```python
from PIL import Image, ImageDraw, ImageFont
import random
import numpy as np
```
2. 定义图形元素,如线条、圆形、矩形、字母和数字:
```python
def draw_random_shape(size, shapes):
shape = random.choice(shapes)
if shape == 'line':
draw.line((random.randint(0, size), random.randint(0, size)),
(random.randint(0, size), random.randint(0, size)), fill=(0, 0, 0))
elif shape == 'circle':
center = (random.randint(0, size), random.randint(0, size))
draw.ellipse((center-10, center-10, center+10, center+10), fill=(0, 0, 0))
# 添加其他形状,如矩形等
def generate_text():
return ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=random.randint(4, 6)))
```
3. 创建验证码图像:
```python
size = 100
image = Image.new('RGB', (size, size), color='white')
draw = ImageDraw.Draw(image)
shapes = ['line', 'circle', 'rectangle'] # 可自定义形状列表
for _ in range(random.randint(4, 6)):
draw_random_shape(size, shapes)
text = generate_text()
font = ImageFont.truetype("arial.ttf", size=random.randint(20, 30)) # 加载字体
text_position = (random.randint(10, size-10), random.randint(10, size-10))
draw.text(text_position, text, font=font, fill=(0, 0, 0))
# 保存验证码图片
image.save('captcha.png')
```
阅读全文