写一个生成验证码的程序
时间: 2024-06-11 11:10:40 浏览: 3
以下是Python语言生成验证码的程序:
```python
import random
import string
from PIL import Image, ImageDraw, ImageFont
# 生成随机字符串
def generate_code(length=4):
# 随机生成数字和字母
code_chars = string.ascii_letters + string.digits
code = ''.join(random.sample(code_chars, length))
return code
# 生成验证码图像
def generate_image(code):
# 图像尺寸
width, height = 120, 50
# 创建图像对象
image = Image.new('RGB', (width, height), color=(255, 255, 255))
# 创建画笔对象
draw = ImageDraw.Draw(image)
# 设置字体
font = ImageFont.truetype('arial.ttf', 36)
# 绘制验证码
draw.text((10, 5), code, font=font, fill=(0, 0, 0))
# 添加干扰线
for i in range(10):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=(0, 0, 0))
# 添加干扰点
for i in range(100):
x = random.randint(0, width)
y = random.randint(0, height)
draw.point((x, y), fill=(0, 0, 0))
# 保存图像
image.save('code.png')
# 测试
code = generate_code()
print(code)
generate_image(code)
```
程序中,生成随机字符串的函数`generate_code`使用了Python标准库中的`string`模块,其中包含了各种字符集,包括大小写字母和数字。`random.sample`函数用于从字符集中随机选择指定长度的字符,随机生成验证码字符串。
生成验证码图像的函数`generate_image`使用了Python第三方库Pillow(也称Python Imaging Library,简称PIL),它提供了丰富的图像处理功能。函数中首先创建了一个白色背景的图像对象,然后使用`ImageDraw`模块创建画笔对象,设置了字体,并在图像上绘制了验证码。接着添加了干扰线和干扰点,增加了验证码的安全性。最后,将生成的图像保存到本地。
在测试代码中,先生成随机验证码字符串,然后调用`generate_image`函数生成图像,并将验证码字符串输出到控制台。程序生成的验证码图像保存为`code.png`文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)