#导包from captcha.image import ImageCaptchafrom PIL import Imageimport randomimport time import os#定义随机方法def random_captcha():#做一个容器captcha_text = []for i in range(4):#定义验证码字符c = random.choice(['0','1','2','3','4','5','6','7','8','9'])captcha_text.append(c)#返回一个随机生成的字符串return ''.join(captcha_text)#生成验证码方法def gen_captcha():#定义图片对象image = ImageCaptcha()#获取字符串captcha_text = random_captcha()#生成图像captcha_img = Image.open(image.generate(captcha_text))return captcha_text,captcha_imgif __name__ == "__main__":#定义图片个数count = 100#定义图片文件夹path = './captcha_image'#如果没有就创建if not os.path.exists(path):os.makedirs(path)#循环创建图片for i in range(count):#定义创建时间now = str(int(time.time()))# print(type(now))#接收字符串和图片text,image = gen_captcha()#定义图片名称filename = text + '_' + now + '.png'#存储图片 os.path.sep 自动获取是文件夹还是文件image.save(path + os.path.sep + filename)print('saved %s' % filename)
1200字范文,内容丰富有趣,写作的好帮手!