生成验证码
import random
import string
from PIL import Image,ImageDraw,ImageFont,ImageFilter
font_path='/opt/WebStorm-172.3544.34/jre64/lib/fonts/DroidSans.ttf '
number=4
size=(100,30)
bgcolor=(255,218,185)
fontcolor=(100,149,237)
linecolor=(0,255,0)
draw_line=True
line_number=(1,3)
def get_text():
source=string.ascii_letters
return ''.join(random.sample(source,number))
def get_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 get_code():
width,height=size
image=Image.new('RGBA',(width,height),bgcolor)
font=ImageFont.truetype(font_path,25)
draw=ImageDraw.Draw(image)
text=get_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:
get_line(draw,width,height)
image=image.filter(ImageFilter.EDGE_ENHANCE_MORE)
image.save('idencode.png','png')
return image,text
if __name__ == '__main__':
get_code()