python+ PIL 生成验证码图片

2/10/2017来源:ASP.NET技巧人气:1655

from PIL import Image , ImageDraw ,ImageFont 

import random


def Verify():
    code = []
    width = 150  ##生成的图片宽度
    height = 60  ###生成的图片高度
    bgcolor = (255,255,255)   ##生成的图片背景色
    img = Image.new('RGB',(width,height),bgcolor)  ##生成图片
    
    draw = ImageDraw.Draw(img)
    while True:
        s = random.randint(48,90)
        if s>57 and s<65:
            continue
        else:
            code.append(chr(s))

            if len(code)==5:
                break 
 
    PRint(code)
    draw.text( (random.randint(10, 20),random.randint(0, 5)),
               code[0],
               (10,7,100),
               font = ImageFont.truetype('simsun.ttc',random.randint(35,50))  )
    draw.text( (random.randint(25, 40),random.randint(0, 5)),
               code[1],
               (10,7,100),
               font = ImageFont.truetype('simsun.ttc',random.randint(35,50))  )
    draw.text( (random.randint(45, 60),random.randint(0, 5)),
               code[2],
               (10,7,100),
               font = ImageFont.truetype('simsun.ttc',random.randint(35,50))  )
    draw.text( (random.randint(65, 80),random.randint(0, 5)),
               code[3],
               (10,7,100),
               font = ImageFont.truetype('simsun.ttc',random.randint(35,50))  )
    draw.text( (random.randint(85, 100),random.randint(0, 5)),
               code[4],
               (10,7,100),
               font = ImageFont.truetype('simsun.ttc',random.randint(35,50))  )
    params = [1 - float(random.randint(1, 2)) / 100,
              0.1,
              0.8,
              0,
              1 - float(random.randint(1, 10)) / 100,
              float(random.randint(1, 2)) / 500,
              0.001,
              float(random.randint(1, 2)) / 500
              ]
  
    img = img.transform((150,60), Image.PERSPECTIVE, params)
    
    
    
    img.show()
    return code
    

            
            
    
if __name__=='__main__':
    Verify()