from PIL import Image, ImageDraw, ImageFont, ImageFile, ImageFilter
import random
def check_code(width=120,height=30,char_length=5,font_file='Monaco.ttf',font_size = 28):
code = [] # 用来存放生成的验证码
img= Image.new(mode='RGB',size=(width,height),color=(255,255,255)) # 生成一个图片
draw = ImageDraw.Draw(img, mode=('RGB')) # 生成一个这个图片的画笔
def rndChar():
"""生成一个字母"""
return chr(random.randint(65,90))
def rndColor():
"""生成一个随机的颜色"""
return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
font = ImageFont.truetype(font_file,font_size) # 创建一个字体样式
for i in range(char_length):
"""开始写文字"""
char = rndChar() # 生成一个字母
code.append(char) # 将字体保存
h = random.randint(0,4)
draw.text([i * width / char_length, h], char, font=font, fill=rndColor()) # 将这个字写上去
for i in range(40):
"""画干扰点"""
draw.point([random.randint(0,width),random.randint(0,height)],fill=rndColor())
for i in range(40):
"""画干扰圆"""
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
for i in range(5):
"""画干扰的线"""
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=rndColor())
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 文件模糊滤镜处理
return img, ''.join(code)
image_object, code = check_code()
stream = BytesIO()
image_object.save(stream, 'png')
stream.getvalue()