Get random string
- Introduce PIL packages, create canvases,
- To create a font, you need to use imagefont.truetype
- Get random background color and font color
- Write the text to the image
- 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