Python generates a verification code

Source: Internet
Author: User

    1. Get random string

    2. Introduce PIL packages, create canvases,
    3. To create a font, you need to use imagefont.truetype
    4. Get random background color and font color
    5. Write the text to the image
    6. Save picture

The code is as follows:

Import Random

Import Image,imagefilter

Import Imagefont

Import Imagedraw

#获取随机字符串

def getchar (len=6):

#新建元组存储获得的字符串

Codelist=[]

For I in range: #获取数字

Codelist.append (str (i))

For I in Range (65,91): #获取A-Z Letters

Codelist.append (str (i))

For I in Range (97,123): #获取a-Z Letters

Codelist.append (str (i))

Code=random.sample (Codelist,len) #截取len个字符, returns a tuple

Verification= '. Join (code) #将元组合并成字符串

Return verification

#创建画布

Im=image.new (' RGB ', (240,60), (255,255,255))

# Create fonts, use Imagefont.truetype

Font=imagefont.truetype (' C:\Windows\Fonts\Arial.ttf ', #字体文件需要有才行)

#获取随机背景颜色和字体颜色

#背景颜色

Def getcolor ():

Return (Random.randint (65,255), Random.randint (65,255), Random.randint (65,255))

#字体颜色

def fontcolor ():

Return (Random.randint (35,127), Random.randint (35,127), Random.randint (35,127))

#将文字写到图像中去

Draw=imagedraw.draw (IM)

For x in range (240):

For Y in range (60):

Draw.point ((x, y), Fill=getcolor ())

For T in range (4):

Draw.text ((* t + ten), GetChar (1), Font=font,fill=fontcolor ())

#保存验证码图像

Im.save (' D:/test.png ')

Note: When running, error code importerror:the _IMAGINGFT C module is not installed error, only need to uninstall PIL, reinstall compiled PIL version can be

Uninstalling Pil:pip Uninstall PIL

Packages that need to be used: import random

Import Image,imagefilter

Import Imagefont

Import Imagedraw

Python generates a verification code

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.