python 点选文字验证码
时间: 2023-09-13 09:11:34 浏览: 67
点选文字验证码是一种常见的图形验证码,可以通过 Python 编程实现。其主要原理是在一张图片中随机生成若干个字符或图形,用户需要通过点击正确的字符或图形来完成验证。以下是一个简单的实现示例:
```python
from PIL import Image, ImageDraw, ImageFont
import random
# 生成随机字符
def random_char():
return chr(random.randint(65, 90))
# 生成随机颜色
def random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 生成验证码图片
def generate_captcha():
width, height = 120, 50
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial.ttf', 36)
chars = []
for i in range(4):
char = random_char()
chars.append(char)
x = random.randint(10, 25) + i * 25
y = random.randint(10, 15)
draw.text((x, y), char, font=font, fill=random_color())
for i in range(10):
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=random_color())
image.save('captcha.png')
return chars
```
该函数会生成一张宽度为 120,高度为 50 的白色背景图片,随机生成 4 个字符并分别绘制在图片上,同时在图片上绘制 10 条随机颜色的直线。最后将图片保存到本地,并返回生成的 4 个字符。用户需要从图片中点击正确的字符来完成验证。