python7-生成验证码

来源:互联网 发布:淘宝村淘扣款比例 编辑:程序博客网 时间:2024/05/24 00:07
from PIL import ImageDraw,ImageFont,ImageFilter,Imageimport randomdef randomChar():    return chr(random.randint(65,90))#随机颜色def randomColor1():    return (random.randint(64,255),random.randint(64,255),random.randint(64,255))#随机颜色2def randomColor2():    return (random.randint(32,127),random.randint(32,127),random.randint(32,127))width = 60 * 4height = 60#创建白色图片image = Image.new('RGB',(width,height),(255,255,255))#font = ImageFont.truetype("Arial.ttf",36)font = ImageFont.truetype('C:/windows/fonts/simsunb.ttf',36)#创建Draw对象,用于向白色背景图片上绘图draw = ImageDraw.Draw(image)#填充每一个像素for x in range(width):    for y in range(height):        draw.point((x,y),fill=randomColor1())#输出文字for i in range(4):    draw.text((60*i+10,10),randomChar(),font=font,fill=randomColor2())image = image.filter(ImageFilter.BLUR)image.save('E:\\Python_project\\image-data\\14.jpeg')

出现的错误:

OSError: cannot open resource 

解决:

需要把指定字体库的系统路径写完整。所以修改为

font = ImageFont.truetype('C:/windows/fonts/simsunb.ttf',36)
两次结果: