当前位置: 首页 > 图灵资讯 > 行业资讯> 想用Python生成验证码,还得看这篇文章

想用Python生成验证码,还得看这篇文章

发布时间:2025-04-06 15:47:05

验证码是web开发中不可缺少的元素,python提供了大量的验证码模块,帮助您快速生成各种验证码。你知道验证码生成的原理吗?所谓知道,也知道为什么。今天,我将向您介绍验证码:

演示环境

·操作系统:windows10

·python版:python 3.7

·代码编辑器:pycharm 2018.2

·使用第三方模块:pillow

验证码的必要元素

1.一张图片

2.文本

3.干扰元素

·线条干扰

·小圆点干扰

熟悉pillow库

既然需要用pillow库制作验证码,首先要熟悉我们需要使用的方法。

1、Image.new():这种方法可以生成三个参数的图片。

·mode:色彩空间模式可以是'RGBA','RGB','L'等等模式

·size:图片尺寸,接收两个整数的元祖

·color:图片的填充颜色可以是red、green等,也可以是rgb的三个整数元祖。即背景颜色

fromPILimportImage
captcha=Image.new('RGB',(1080,900),(255,255,255)

以上代码创建了1亿RGB的颜色空间模式,大小为1080*900,背景颜色为白色图片。

2、Image.save():将图片保存到本地

·fp:本地文件名

·format:可选参数,制定文件后缀名。

fromPILimportImage
captcha=Image.new('RGB',(1080,900),(255,255,255)
#captcha.save('captcha.png')
captcha.save('captcha',format='png')

上述两种方法的保存效果相同。

3、Image.show():显示图片,会调用电脑自带的显示图片的软件。

4、ImageFont.truetype():加载字体文件。生成字体对象。

fromPILimportImageFont
#字体文件路径字体大小
font=ImageFont.truetype('simkai.ttf',16)

5、ImageDraw.Draw():画笔对象的生成。

fromPILimportImage,ImageDraw
captcha=Image.new('RGB',(1080,900)'red')
draw=ImageDraw.Draw(captcha)

在captcha的图片上创建了一个画笔,我们在这张图片上画任何东西都会使用这个画笔对象。

6、ImageDraw.Draw().text():在图片上绘制给定的字符

fromPILimportImage,ImageDraw,ImageFont
captcha=Image.new('RGB',(1080,900)'red')
font=ImageFont.truetype('simkai.ttf',16)
draw=ImageDraw.Draw(captcha)
#在字符绘制位置绘制字符,制定字符颜色
draw.text(0,0)'helloworld',font=font,fill='black')

7、ImageDraw.Draw().line():画出图片上的线条

fromPILimportImage,ImageDraw,ImageFont
captcha=Image.new('RGB',(1080,900)'red')
draw=ImageDraw.Draw(captcha)
#线条起点线条终点
draw.line((0,0),(1080,900),fill='black')

8、ImageDraw.Draw().point():在图片上绘制点

fromPILimportImage,ImageDraw,ImageFont
captcha=Image.new('RGB',(1080,900),'red')
font=ImageFont.truetype('simkai.ttf',16)
draw=ImageDraw.Draw(captcha)
#点的位置颜色
draw.point((500,500),fill='black')

我们将使用上述方法来制作我们的验证码。当然,pillow肯定不止这些方法,这里我们只列出这些。

制作验证码

1、首先,我们定义一个类,初始化一些所需的参数。

importstring
classCaptcha():
'''
captcha_size:验证码图片尺寸
font_size:字体大小
text_number:验证码中的字符数
line_number:线条个数
background_color:验证码的背景颜色
sources:取样字符集。验证码中的字符是从这个中随机选择的
save_format:验证码保存格式
'''
def__init__(self,captcha_size=(150,100),font_size=30,text_number=4,line_number=4,background_color=(255,
255,255),sources=None,save_format='png'):
self.text_number=text_number
self.line_number=line_number
self.captcha_size=captcha_size
self.background_color=background_color
self.font_size=font_size
self.format=save_format
ifsources:
self.sources=sources
else:
self.sources=string.ascii_letters+string.digits

以下是string模块。

·string.ascii_letters: 得到a-zA-Z所有字符

·string.digits: 获得0-9所有数字

2、从sources随机获取字符

importrandom
defget_text(self):
text=random.sample(self.sources,k=self.text_number)
return''.join(text)

random.sample()方法:从第一个参数中随机获取字符。获取的数量由第二个参数指定。

3、随机获取绘制字符的颜色

defget_font_color(self):
font_color=(random.randint(0,150),random.randint(0,150),random.randint(0,150))
returnfont_color

4、随机获取干扰线的颜色

defget_line_color(self):
line_color=(random.randint(0,250),random.randint(0,255),random.randint(0,250))
returnline_color

5、编写和绘制文本的方法

defdraw_text(self,draw,text,font,captcha_width,captcha_height,spacing=20):
'''
在图片上绘制传入的字符
:paramdraw:画笔对象
:paramtext:所有绘制的字符
:paramfont:字体对象
:paramcaptcha_width:验证码的宽度
:paramcaptcha_height:验证码的高度
:paramspacing:每个字符之间的间隙
:return:
'''
#得到这个字符的高度和宽度
text_width,text_height=font.getsize(text)
#得到每个字体的大致宽度
every_value_width=int(text_width/4)
#这个字符的总长度
text_length=len(text)
#每两个字符之间都有间隙,获得总间隙
total_spacing=(text_length-1)*spacing
iftotal_spacing+text_width>=captcha_width:
raiseValueError("超过图片宽度的字体加中间间隙!")

#获得第一个字符绘制位置
start_width=int((captcha_width-text_width-total_spacing)/2)
start_height=int((captcha_height-text_height)/2)
#依次绘制每个字符
forvalueintext:
position=start_width,start_height
print(position)
#画text
draw.text(position,value,font=font,fill=self.get_font_color())
#改变下一个字符的开始绘制位置
start_width=start_width+every_value_width+spacing

6、画线的方法

defdraw_line(self,draw,captcha_width,captcha_height):
'''
绘制线条
:paramdraw:画笔对象
:paramcaptcha_width:验证码的宽度
:paramcaptcha_height:验证码的高度
:return:
'''
#随机获取开始位置的坐标
begin=(random.randint(0,captcha_width/2),random.randint(0,captcha_height))
#随机获取结束位置的坐标
end=(random.randint(captcha_width/2,captcha_width),random.randint(0,captcha_height))
draw.line([begin,end],fill=self.get_line_color())

7、绘制小圆点

defdraw_point(self,draw,point_chance,width,height):
'''
绘制小圆点
:paramdraw:画笔对象
:parampoint_chance:画小圆点的概率是point_chance/100
:paramwidth:验证码宽度
:paramheight:验证码高度
:return:
'''
#根据概率随机绘制小点
forwinrange(width):
forhinrange(height):
tmp=random.randint(0,100)
iftmp<point_chance:
draw.point((w,h),fill=self.get_line_color())

8、制作验证码

defmake_captcha(self):
#获取验证码的宽度和高度
width,height=self.captcha_size
#生成一张图片
captcha=Image.new('RGB',self.captcha_size,self.background_color)
#获取字体对象
font=ImageFont.truetype('simkai.ttf',self.font_size)
#获取画笔对象
draw=ImageDraw.Draw(captcha)
#得到绘制的字符
text=self.get_text(
#绘制字符
self.draw_text(draw,text,font,width,height)
#绘制线条
foriinrange(self.line_number):
self.draw_line(draw,width,height)
#画小圆点10是概率10/100,概率10%
self.draw_point(draw,10,width,height)
#保存图片
captcha.save('captcha',format=self.format)
#显示图片
captcha.show()

这样,我们就生成了我们的图片验证码,效果图:

所有代码都上传到Github:https://github.com/MiracleYoung/You-are-Pythonista/tree/master/PythonExercise/App/

captcha_project

python培训视频众多,全部在python学习网,欢迎在线学习!

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09