python自动生成验证码

tech2023-02-05  103

导入的包

import numpy as np import random as ran from PIL import Image,ImageDraw,ImageFont,ImageFilter import time

随机颜色

def rndColor2(): return (ran.randint(32, 127), ran.randint(32, 127), ran.randint(32, 127)) def rndColor(): return (ran.randint(64, 255), ran.randint(64, 255), ran.randint(64, 255))

生成数字和字母,默认为六位

返回一个列表,按时间生产一个图片

#默认6个数字加字母 def seccode(index=6): #创建随机数 index=int(index) lett=[chr(i) for i in np.random.randint(65, 90,index)]+[str(i) for i in np.random.randint(0, 9, index)] #随机切index数 getColor=ran.sample(lett,index) # *n代表生成几个随机字,与下面生成字符的n对应,, #width的像素也可以固定长度为240像素 width = 60 * 4 height = 60 # 生成图片 image = Image.new('RGB', (width, height), (255, 255, 255)) # 创建Font对象字体: font = ImageFont.truetype(r'E:\msyh.ttf',30) # # 创建Draw对象: draw = ImageDraw.Draw(image) #填充每个像素(画点): for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) #输出文字: for t in range(len(getColor)): #创建随机高度限高20,我60像素 highly=np.random.randint(3,20,1) #创建随机长度限长40,我240像素 length=np.random.randint(6,10,1) length_t = np.random.randint(3, 10, 1) print((40-length)*t+length_t,highly) #文字位置长度,高度 draw.text(((40-length)*t+length_t,highly),getColor[t],font=font,fill=rndColor2()) # 模糊: image = image.filter(ImageFilter.SMOOTH_MORE) #生成图片位置,名字我用是时间戳 image.save('{}.jpg'.format(int(time.time())), 'jpeg') #显示图片 # image.show() return getColor

判断验证是否正确,返回为True,false

#value是原值,tests是输入的值 def Validation(value,tests): tests=list(tests) t=0 for i in range(len(value)): if ord(value[i])>=0 and ord(value[i])<=57: if value[i]==tests[i]: t+=1 else: if ord(value[i])==ord(tests[i]) or ord(value[i])==ord(tests[i])+32 or ord(value[i])==ord(tests[i])-32: t+=1 if len(value) == t: return True else: return False

图片样式显示

最新回复(0)