Python2生成简单验证码 | Blurred code

Python2生成简单验证码

panda

2016/04/23

LastMod:2020/03/22

Categories: Python

使用python2.7环境编写,原因是Python2.7内置了PIL库,而Python3需要手动安装Pillow库,且Pillow还依赖几个其他的库。功能很简单,所以就不想折腾了。

生成验证码分为下列步骤:

#!/usr/bin/env python
# encoding: utf-8

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
def get_chars():
    char_list=[random.choice(string.ascii_letters) for i in range(4)]
    return (char_list)
def get_color():
    return(random.randint(30,106),random.randint(30,100),random.randint(30,100))
def create_pic_code():
    parameter={'size':(120,30),
               'img_type':'jpeg',
              'bg_color':(180,180,180),
               }
    img=Image.new('RGB',parameter['size'],parameter['bg_color'])
    draw=ImageDraw.Draw(img)

    #draw text
    chars=get_chars()
    font=ImageFont.truetype('./SourceCodePro-Medium.ttf',30)
    for i in range(len(chars)):
        draw.text((30*i + 10,0),chars[i],font=font,fill=get_color())
    #background
    for tmp in range(2000):
        draw.point((random.randint(0,parameter['size'][0]),random.randint(0,parameter['size'][1])),fill=get_color())

    ##filter
    #img=img.filter(ImageFilter.BLUR)
    img.save('chars.jpg','jpeg')
if __name__=='__main__':
    create_pic_code()