Python是生成动态图像的一种常用语言。以下是使用Python生成验证码的步骤:
下面是一个使用Python生成验证码的示例代码:
from PIL import Image, ImageDraw, ImageFont
import random
# 随机字符串
def random_str():
source = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')
return ''.join(random.sample(source, 4)) # 随机生成4个字符
# 随机颜色
def random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 生成验证码图片
def create_captcha():
# 创建图片
width, height = 120, 50
image = Image.new('RGB', (width, height), (255, 255, 255))
font = ImageFont.truetype('arial.ttf', 40) # 字体
draw = ImageDraw.Draw(image)
# 填充文字
for i in range(4):
draw.text((20 + i * 25, 10), random_str()[i], font=font, fill=random_color())
# 添加干扰线
for i in range(random.randint(2, 5)):
x1, y1 = random.randint(0, width), random.randint(0, height)
x2, y2 = random.randint(0, width), random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=random_color())
# 添加噪点
for i in range(50):
draw.point((random.randint(0, width), random.randint(0, height)), fill=random_color())
image.save('captcha.png', 'PNG') # 保存图片
create_captcha() # 调用函数生成验证码图片