怎么随机生成验证码图片
时间: 2023-09-01 19:07:39 浏览: 57
你可以使用 Python 的 Pillow 库来随机生成验证码图片。以下是一个简单的示例代码:
```python
from PIL import Image, ImageDraw, ImageFont
import random
# 生成随机验证码
def generate_verification_code(length=4):
code = ''
for i in range(length):
code += str(random.randint(0, 9))
return code
# 生成验证码图片
def generate_verification_image(code):
# 设置图片大小和背景色
width, height = 120, 50
bg_color = (255, 255, 255) # white
# 创建图片对象和画笔对象
im = Image.new('RGB', (width, height), bg_color)
draw = ImageDraw.Draw(im)
# 生成随机颜色
def random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 添加噪点
def draw_noise():
for x in range(width):
for y in range(height):
if random.random() > 0.8:
draw.point((x, y), fill=random_color())
# 添加干扰线
def draw_lines():
line_num = random.randint(2, 4)
for i in range(line_num):
start_x = random.randint(0, width // 2)
start_y = random.randint(0, height)
end_x = random.randint(width // 2, width)
end_y = random.randint(0, height)
draw.line((start_x, start_y, end_x, end_y), fill=random_color(), width=3)
# 添加验证码文字
font = ImageFont.truetype('arial.ttf', 36)
for i, c in enumerate(code):
x = (width // len(code)) * i + 10
y = random.randint(0, height // 2)
draw.text((x, y), c, font=font, fill=random_color())
# 添加噪点和干扰线
draw_noise()
draw_lines()
# 返回图片对象
return im
# 测试代码
if __name__ == '__main__':
code = generate_verification_code()
print(code)
im = generate_verification_image(code)
im.show()
```
运行上述代码,将会生成一个随机验证码图片。你可以根据需要调整图片的大小、背景色、干扰线数量等参数。
相关推荐
![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)