网站为例防止恶意注册、发帖等恶意操作而设置了验证码,其原理是将一串随机产生的数字或字母生成一幅图片,图片上加一下干扰元素。本文介绍利用python生成一个验证码,其中代码做了注释并于相关知识的解答
1、python环境
2、涉及到的python库需要 pip install 包名
安装
pip install pillow
import random,string,sys,math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import os
font_path = 'C:\Windows\Fonts\simfang.ttf' #字体位置
number = 5 #生成几位数的验证码
size =(100,40) #生成验证码的图像大小
bgcolor = (255,255,255) #生成的背景色(白色)
draw_line = True #是否要加干扰线和干扰点
path = "vertification.png" #验证码存放位置
def random_text ():
source = list(string.ascii_letters)
#print(source)
for index in range(0,10):
source.append(str(index))
return ''.join(random.sample(source,1))
def random_line(drawpen,width,height):
for i in range(random.randint(4,8)):
linecolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #干扰线的颜色随机
begin = (random.randint(0,width),random.randint(0,height)) #干扰线的位置随机
end = (random.randint(0,width),random.randint(0,height))
drawpen.line([begin,end],fill = linecolor)
def random_point(drawpen,width,height):
for i in range(20):
linecolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #干扰点的颜色随机
begin = (random.randint(0,width),random.randint(0,height)) #干扰点的位置随机
end = (random.randint(0,width),random.randint(0,height))
drawpen.point([begin,end],fill = linecolor)
def get_code():
x_start = 2
y_start = 0
width,height = size #验证码的宽和高
image = Image.new('RGBA',(width,height),bgcolor) #创建图片
font = ImageFont.truetype(font_path,25) #设置验证码的字体
drawpen = ImageDraw.Draw(image) #生成画笔
for i in range(number):
fontcolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #验证码字体的颜色随机
text = random_text()
#font_width,font_height = font.getsize(text)
x = x_start + i * int(width / (number))
y = random.randint(y_start, int(height / 2))
drawpen.text((x, y), text = text,font = font,fill = fontcolor)
# drawpen.text(((width - font_width) / number,(height - font_height) / number),text = text,font = font,fill = fontcolor)
if draw_line:
random_line(drawpen,width,height)
random_point(drawpen,width,height)
# image = image.transform((width + 20,height + 20),Image.AFFINE,(1,-0.3,0,-0.1,1,0),Image.BILINEAR) #创建扭曲
# image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #扭曲,边界加强
image.save(path)
os.startfile(path)
if __name__ == "__main__":
get_code()
完整代码:(有后续补充的 详细注释)
https://download.csdn.net/download/weixin_45386875/15158218
其他python应用实例见:https://blog.csdn.net/weixin_45386875/article/details/113766276