from PIL import Image, ImageDraw, ImageFont from io import BytesIO import random def get_valid_img(request): # 生成随机颜色 def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 生成随机背景色的图片 -- 改版: 背景色为幽灵白 img = Image.new('RGB', (360, 38), (248, 248, 255)) draw = ImageDraw.Draw(img) font = ImageFont.truetype('static/font/f1.TTF', 32) code = "" # 验证码明文 # 生成随机验证码 for i in range(6): random_num = str(random.randint(0, 9)) # 生成随机数字 random_up = chr(random.randint(65, 90)) # 生成随机大写字母 random_low = chr(random.randint(97, 122)) # 生成随机小写字母 # 随机选择数字,大写字母,小写字母中的一个 random_char = random.choice([random_low, random_up, random_num]) # 在生成的随机背景色图片上绘制随机颜色的随机验证码 draw.text((i * 51 + 50, 0), random_char, get_random_color(), font=font) # 保存生成的随机验证码 code += random_char print("验证码是: ", code) width = 350 height = 38 # 添加噪线 for i in range(2): x1 = random.randint(0, width) x2 = random.randint(0, width) y1 = random.randint(0, height) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=get_random_color()) # 添加噪点 for i in range(30): draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color()) x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color()) # 将生成的验证码图片保存在内存中 f = BytesIO() # 句柄 img.save(f, 'png') # 保存 data = f.getvalue() # 验证码图片数据 # 将验证码保存在各自的session中,方便不同浏览器之间进行验证 request.session['code'] = code return HttpResponse(data)