import randomimport stringfrom PIL import Image,ImageDraw,ImageFont,ImageFilter # 字体的位置font_path = "/Library/Fonts/Arial.ttf"# 验证码的位数number = 4# 生成图片的大小size = (100,30)# 图片背景颜色-白色bgcolor = (255,255,255)# 验证码字体颜色——蓝色fontcolor = (0,0,255)# 干扰线的颜色——红色linecolor = (255,0,0)# 是否加入干扰线draw_line = True# 图片上干扰线的颜色line_number = (1,5) def gene_text(): # 获取26个英文字母 source = list(string.ascii_letters) for index in range(0, 10): # 获取10个数字 source.append(str(index)) return ‘‘.join(random.sample(source, number)) # number是生成验证码的位数 #用来绘制干扰线def gene_line(draw,width,height): begin = (random.randint(0, width), random.randint(0, height)) end = (random.randint(0, width), random.randint(0, height)) draw.line([begin, end], fill = linecolor) #生成验证码def gene_code(k): # 宽和高 width,height = size # 创建图片 image = Image.new(‘RGBA‘,(width,height),bgcolor) # 验证码的字体 font = ImageFont.truetype(font_path,25) # 创建画笔 draw = ImageDraw.Draw(image) # 生成字符串 text = gene_text() font_width, font_height = font.getsize(text) # 填充字符串 draw.text(((width - font_width) / number, (height - font_height) / number),text,\ font= font,fill=fontcolor) if draw_line: gene_line(draw,width,height) # 创建扭曲 image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR) # 滤镜,边界加强 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 保存验证码图片 image.save(‘%d.png‘%k) if __name__ == "__main__": # 循环创建验证码图片 for i in range(0,1000): gene_code(i)
时间: 2024-11-09 02:45:20