import random,string,sys,math
from PIL import Image, ImageDraw, ImageFont, ImageFilter
font_path='C:\Windows\Fonts\simkai.ttf' #设置字体
number=4
size=(80,30)
bgcolor=(137,215,188)
fontcolor=(103,171,214)
linecolor=(244,109,144)
draw_line=True #加干扰线
line_number=(1,5) #干扰线范围
#随机生成字符串
def gene_text():
source=list(string.ascii_letters)#a-z
for index in range(0,10): #加入0-9
source.append(str(index))
return ''.join(random.sample(source,number)) #连起来 中间 没有间隔
def gene_line(draw,width,height):
begin=(random.randint(0,width), random.randint(0,height))
end=(random.randint(0,width),random.randint(0,height))
draw.line([begin,end], fill=linecolor)
#生成验证码
def gene_code():
width,height=size #宽与高
image=Image.new('RGBA',(width,height),bgcolor)
font=ImageFont.truetype(font_path,25)
draw=ImageDraw.Draw(image)
text=gene_text()
font_width,font_height=font.getsize(text)
draw.text(((width-font_width)/number,(height-font_height)/number),text,font=font,fill=fontcolor) #填充字符串
if draw_line:
gene_line(draw,width,height)
image=image.transform((width+20,height+10), Image.AFFINE,(1,-0.3,0,-0.1,1,0),Image.BILINEAR)
image=image.filter(ImageFilter.EDGE_ENHANCE_MORE)
image.save("2.png")
if __name__=="__main__":
gene_code()
python生成验证码
最新推荐文章于 2024-07-30 17:23:09 发布