import random from PIL import Image, ImageDraw, ImageFont, ImageFilter from io import BytesIO # 生成验证码图片的高度和宽度 size = (129, 53) # 背景颜色,默认为白色 bg_color = (255, 255, 255) # 干扰线颜色。默认为红色 linecolor = (0, 0, 0) # 是否要加入干扰线 draw_line = True # 加入干扰线条数的上下限 line_number = (1, 5) # 随机色 def getRandomColor(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) return (r, g, b) # 数字 小写 大写 里随机一个 def getRandomChar(): random_num = str(random.randint(0, 9)) random_lower = chr(random.randint(97, 122)) random_upper = chr(random.randint(65, 90)) random_char = random.choice([random_num, random_lower, random_upper]) return random_char # 用来绘制干扰线 def gene_line(draw, width, height): begin = (random.randint(0, width), random.randint(0, height)) end = (random.randint(0, width), random.randint(0, height)) # begin = (0, random.randint(0, height)) # 起点 # end = (74, random.randint(0, height)) # 终点 linecolor = getRandomColor() while linecolor == bg_color: linecolor = getRandomColor() draw.line([begin, end], fill=linecolor, width=random.choice(range(1, 3))) # number验证码位数 def getcode(number=4): width, height = size # 宽和高 # 背景色 bg_color = getRandomColor() image = Image.new('RGBA', size, bg_color) # 创建图片 import os path = os.path.join(os.getcwd(), 'utils', 'Arial.ttf') print(os.path.exists(path), '0-----------') font = ImageFont.truetype(font='arial.ttf', size=36) # 验证码的字体 draw = ImageDraw.Draw(image) # 创建画笔 text = '' # 随机的字符、颜色 for i in range(number): code = getRandomChar() code_color = getRandomColor() while code_color == bg_color: code_color = getRandomColor() # 字体的大小 # font_width, font_height = font.getsize(code) # 根据坐标填充字符 draw.text((10 + 30 * i, 3), code, font=font, fill=code_color) # 填充字符串 text = text + code if draw_line: gene_line(draw, width, height) # image = image.transform((width + 30, height + 10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 创建扭曲 # 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) # 滤镜,边界加强 bytes = BytesIO() # 内存 image.save(bytes, format='png') # 保存验证码图片 return bytes.getvalue(), text # 获得二进制数据,