#coding=utf-8
import random,string
from PIL import Image,ImageDraw,ImageFont,ImageFilter
font_path="C:\\Windows\\Fonts\\simfang.ttf"
number=4#生成验证码的位数
size=(80,30)
bgcolor=(255, 228, 225)
fontcolor= (132, 112, 255)
linecolor=(0,0,0)
draw_line=True
line_number=(2,6)
def gene_text():
source= list(string.ascii_letters)
for index in range(0,10):
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('idencode.png')
if __name__=="__main__":
gene_code()
python随机生成四位验证码
猜你喜欢
转载自blog.csdn.net/ur_ytii/article/details/112991281
今日推荐
周排行