Python generates 4-bit captcha picture

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.