python2 生成验证码图片

使用pillow或者pil库编写

#coding:utf-8

#use pillow or pil
try:
    from PIL import Image, ImageDraw, ImageFont, ImageEnhance,ImageFilter
except ImportError:
    import Image, ImageDraw, ImageFont, ImageEnhance,ImageFilter

import string,random

fontPath = "C:/windows/fonts/"

#获取随即四个字母
def getRandomChar():
    return [random.choice(string.letters) for _  in range(4)]

#获取颜色
def getRandomColor():
    return (random.randint(30,100),random.randint(30,100),random.randint(30,100))

#获取验证码图片
def getCodePiture():
    width = 240
    height = 60
    #创建画布
    image = Image.new('RGB',(width,height),(180,180,180))
    font = ImageFont.truetype(fontPath+'simhei.ttf',40)
    draw = ImageDraw.Draw(image)
    #创建验证码对象
    code = getRandomChar()
    #把验证码放在画布上
    for t in range(4):
        draw.text((60*t+10,0),code[t],font=font,fill=getRandomColor())
    #填充噪点
    for _ in range(random.randint(1500,3000)):
        draw.point((random.randint(0,width),random.randint(0,height)),fill=getRandomColor())
    #模糊处理
    image = image.filter(ImageFilter.BLUR)
    #保存名字为验证码图片
    image.save("".join(code)+'.jpg','jpeg')


if __name__ == "__main__":
    print getCodePiture()
posted on 2017-09-07 21:52  神秘藏宝室  阅读(246)  评论(0编辑  收藏  举报

 >>>转载请注明出处<<<