Import Random
Import string
From PIL import Image,imagedraw,imagefont,imagefilter
# The location of the font
Font_path = "/library/fonts/arial.ttf"
# Number of digits of the verification code
Number = 4
# Create a picture size
Size = (100,30)
# Picture Background Color-White
bgcolor = (255,255,255)
# captcha Font Color--Blue
FontColor = (0,0,255)
# The color of the interference line--red
LineColor = (255,0,0)
# whether to join the interference line
Draw_line = True
# The color of the interference line on the picture
Line_number = (1,5)
Def gene_text ():
# get 26 Letters of English
Source = List (string.ascii_letters)
For index in range (0, 10):
# Get 10 numbers
Source.append (str (index))
Return '. Join (Random.sample (source, number)) # number is the digit that generated the verification code
#用来绘制干扰线
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 (k):
# Width and height
Width,height = Size
# Create a picture
Image = Image.new (' RGBA ', (width,height), bgcolor)
# The font of the verification code
Font = Imagefont.truetype (font_path,25)
# Create brushes
Draw = Imagedraw.draw (image)
# Generate string
Text = Gene_text ()
Font_width, font_height = font.getsize (text)
# Fill String
Draw.text (((width-font_width)/number, (Height-font_height)/number), text,\
Font= Font,fill=fontcolor)
If Draw_line:
Gene_line (Draw,width,height)
# Create Distortions
Image = Image.transform ((width+20,height+10), Image.affine, (1,-0.3,0,-0.1,1,0), image.bilinear)
# Filters, Border enhancement
Image = Image.filter (Imagefilter.edge_enhance_more)
# Save Verification Code picture
Image.Save ('%d.png '%k)
if __name__ = = "__main__":
# Loop to create a captcha picture
For I in Range (0,1000):
Gene_code (i)
Python generates 4-bit captcha picture