代码在下。
from random import randint,choice
from PIL import Image,ImageDraw,ImageFont
from io import BytesIO
from string import printable
def pillow_test():
#设置选用的字体
font_path = 'simhei.ttf'
font_color = (randint(150, 200), randint(0, 150), randint(0, 150))
line_color = (randint(0, 150), randint(0, 150), randint(150, 200))
point_color = (randint(0, 150), randint(50, 150), randint(150, 200))
#设置验证码的宽与高
width, height = 100, 34
image = Image.new("RGB",(width, height),(200,200,200))
font = ImageFont.truetype(font_path,height - 10)
draw = ImageDraw.Draw(image)
#生成验证码
text = "".join([choice(printable[:62]) for i in range(4)])
font_width, font_height = font.getsize(text)
print(text)
#把验证码写在画布上
draw.text((10, 10), text, font=font, fill=font_color)
#绘制干扰线
for i in range(0, 5):
draw.line(((randint(0, width), randint(0, height)),
(randint(0, width), randint(0, height))),
fill=line_color, width=2)
# 绘制点
for i in range(randint(100, 1000)):
draw.point((randint(0, width), randint(0, height)), fill=point_color)
#输出
out = BytesIO()
image.save(out,format='jpeg')#将验证码保存在内存中
content = out.getvalue()
out.close()
#f = open('验证码.jpg', 'wb')
#image.save(f)
#f.close()#将验证码保存在本地
return text, content
django中views可以直接调用这个函数来实现前端页面的验证码