python编写验证码程序简单

   2025-08-03 00
核心提示:Python编写验证码程序简介:使用Python的图像处理库和随机函数生成包含数字、字母或符号的验证码图片,通过干扰线条、噪点等方式增加安全性。用户输入验证码,程序比对输入与生成的验证码是否一致,实现验证功能。

python

import random

import string

from PIL import Image, ImageDraw, ImageFont

生成随机字符串验证码函数

def generate_captcha(length=4):

# 定义字符集,包含大小写字母和数字

chars = string.ascii_letters + string.digits

captcha = ’’.join(random.choice(chars) for i in range(length))

return captcha

python编写验证码程序简单

生成验证码图片函数

def generate_captcha_image(captcha, font_path=’arial.ttf’, font_size=30, width=120, height=60):

# 创建空白图片对象

image = Image.new(’RGB’, (width, height), color=(255, 255, 255))

# 创建绘图对象

draw = ImageDraw.Draw(image)

# 设置字体对象,用于在图片上绘制文字

font = ImageFont.truetype(font_path, font_size)

# 在图片上绘制文字验证码

draw.text((width // 2 - font_size // 2, height // 2 - font_size // 4), captcha, font=font, fill=(0, 0, 0))

# 添加干扰线条和噪点,增加识别难度

for i in range(random.randint(5, 10)):

draw.line([(random.randint(0, width), random.randint(0, height)), (random.randint(0, width), random.randint(0, height))], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=random.randint(1, 3))

draw.point([(random.randint(0, width), random.randint(0, height))], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

# 保存图片到文件或返回图片对象(用于网络应用)

image.save(’captcha.png’) # 保存图片到文件,文件名默认为captcha.png

return image # 返回图片对象,用于网络应用等场景

测试程序

captcha = generate_captcha() # 生成随机验证码字符串

image = generate_captcha_image(captcha) # 生成验证码图片对象或保存到文件

该程序使用PIL库生成一张包含随机验证码字符串的图片,并在图片上添加干扰线条和噪点以增加识别难度,可以根据需要调整生成的验证码长度、字体大小、图片大小等参数,生成的图片可以保存到本地文件或通过返回图片对象用于其他应用场景。
 
举报评论 0
 
更多>同类资讯
推荐图文
推荐资讯
点击排行
友情链接
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  版权声明  |  网站地图  |  排名推广  |  广告服务  |  积分换礼  |  网站留言  |  RSS订阅  |  违规举报