Python3.4的Pillow库实现验证码图片

转自 http://blog.csdn.net/bin381/article/details/41969493

 

from PIL import Image,ImageDraw, ImageFont, ImageFilter  
import random  
_letter_cases = 'abcdefghjkmnpqrstuvwxy'  
_upper_cases = _letter_cases.upper()  
_numbers = ''.join(map(str, range(3, 10)))  
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))  
  
def creat_validata_code(size=(120,30),chars=init_chars,img_type='jpg',  
                        mode='RGB',bg_color=(255,255,255),fg_color=(0,0,255),  
                            font_size=18,font_type='arial.ttf',  
                            length=4,draw_lines=True,n_line=(1,2),  
                            draw_points=True,point_chance=2):  
    width,height = size;  
    img = Image.new(mode, size, bg_color);  
    draw = ImageDraw.Draw(img)  
      
    def get_chars():  
        return random.sample(chars,length)  
      
    def creat_line():  
        line_num = random.randint(*n_line)#sign that the param is a list  
          
        for i in range(line_num):  
            begin = (random.randint(0, size[0]), random.randint(0, size[1]))  
            end = (random.randint(0, size[0]), random.randint(0, size[1]))  
            draw.line([begin, end], fill=(0, 0, 0))  
      
    def create_points():  
        chance = min(100, max(0, int(point_chance)))  
        for w in range(width):  
            for h in range(height):  
                tmp = random.randint(0, 100)  
                if tmp > 100 - chance:  
                    draw.point((w, h), fill=(0, 0, 0))  
      
    def create_strs():  
        c_chars = get_chars()  
        strs = ' %s ' % ' '.join(c_chars)  
        font = ImageFont.truetype(font_type, font_size)  
        font_width, font_height = font.getsize(strs)  
        draw.text(((width - font_width) / 3, (height - font_height) / 3),  
                    strs, font=font, fill=fg_color)  
        return ''.join(c_chars)  
      
    if draw_lines:  
        creat_line()  
    if draw_points:  
        create_points()  
    strs = create_strs()  
  
    params = [1 - float(random.randint(1, 2)) / 100,  
              0,  
              0,  
              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(size, Image.PERSPECTIVE, params)  
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  
    return img, strs  
  
if __name__ == '__main__':  
    code_img,capacha_code= creat_validata_code()  
    code_img.save('xx.jpg','JPEG')  

  

 

参考链接:

  • http://blog.csdn.net/csapr1987/article/details/7728315
  • https://pillow.readthedocs.org/
  • https://pypi.python.org/packages/3.4/P/Pillow/Pillow2.6.1.win32py3.4.exe#md5=fc2c0751e7782433d02d093f8f3a8de5(Pillow-2.6.1.win32-py3.4.exe的安装地址)
 最后        注意的是如果机器上没有arial.ttf 这个字体的话,会报一个ImageFont的错误出来,用机子有的字体就可以解决

你可能感兴趣的