import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFilter
import random
# 随机字母:
def rndChar():
return chr(random.randint(65, 90))
# 随机颜色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
'''生成验证码,fontFile为字体文件,saveImageFile为生成验证码图片文件
'''
def GetVerifyCode(fontFile,saveImageFile,width = 60 * 4, height = 60):
fontFile = unicode(fontFile,'utf8')
saveImageFile = unicode(saveImageFile,'utf8')
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype(fontFile, 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save(saveImageFile, 'jpeg');
#测试代码
fontfile='D:\Arial.ttf'
savefile='D:\code1.jpg'
GetVerifyCode(fontfile,savefile)
请请参考PIL官方文档: