利用python的pillow库简单的生成验证码
#生成指定长度的随机字符
def procharacter(length):
numbers = "".join(random.choice(charactes) for _ in range(length))
return numbers
#生成随机颜色
def color():
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
return (r,g,b)
def main(size=(200,100),characternumber=6,bgcolor=(255,255,255)):
#创建空白图象和绘图对象
image = Image.new('RGB',size,bgcolor) #k空白图象
draw = ImageDraw.Draw(image)
#生成并计算宽度和高度
text = procharacter(characternumber) #生成文本
font = ImageFont.truetype("c:\\windows\\fonts\\tahoma.ttf",48)
width,height = draw.textsize(text,font) #返回text在font字体下的大小
if width+2*characternumber>size[0] or height>size[1]:
print("尺寸不合法")
return
#绘制随机字符串中的字符
startx = 0 #从0开始画
widtheach = width // characternumber
for i in range(characternumber):
startx += widtheach + 1 + random.randint(2,3)
#每个字符的y坐标随机生成
position = (startx,(size[1]-height)//2+random.randint(-10,10))
draw.text(xy=position,text = text[i],font=font,fill=color())
#像素位置微调,实现扭曲的效果
imagefinal = Image.new('RGB',size,bgcolor)
pixelsfinal = imagefinal.load()
pixelstemp = image.load()
for y in range(size[1]):
offset = random.randint(-1,0)
for x in range(size[0]):
newx = x + offset
if newx<0:
newx = 0
pixelsfinal[newx,y] = pixelstemp[x,y] #像素
#绘制随机颜色的干扰像素
draw = ImageDraw.Draw(imagefinal)
for i in range(int(size[0]*size[1]*0.1)): #噪点的密度
draw.point((random.randrange(size[0]),random.randrange(size[1])),fill=color())
#绘制八条干扰的直线
for i in range(8):
s = (0,random.randrange(size[1]))
e = (size[0],random.randrange(size[1]))
draw.line([s,e],fill=color(),width=1)
#绘制八条干扰的曲线
for i in range(8):
s = (-50,-50)
e = (size[0]+10,random.randint(0,size[1]+10))
draw.arc(s+e,0,360,fill=color())
#保存
imagefinal.save("G://验证码.jpg")
imagefinal.show()
if __name__ == '__main__':
main((200,100),6,(255,255,255))