pillow模块 (PIL) 生成验证码
验证码源码:
def v_code(request): from PIL import Image, ImageDraw, ImageFont import random # 定义一个生成随机颜色的函数 def get_color(): return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) # 生成一个图片对象 img_obj = Image.new( "RGB", (250, 35), color=get_color() ) # 在图片中加文字 # 生成一个画笔对象 draw_obj = ImageDraw.Draw(img_obj) # 加载字体文字 font_obj = ImageFont.truetype("static/font/kumo.ttf", size=28) # for 循环5次,每次写一个随机字符 tmp_list = [] for i in range(5): n = str(random.randint(0, 9)) # 生成一个随机数字 l = chr(random.randint(97, 122)) # 生成一个随机小写字母 u = chr(random.randint(65, 90)) # 生成一个随机大写字母 r = random.choice([n, l, u]) # 随机选取 tmp_list.append(r) # 存入列表 为下面加入session做准备 draw_obj.text( (i * 48 + 20, 0), # 位置 r, # 内容 get_color(), # 颜色 font=font_obj # 字体 ) # 拿到随机验证码 拼接成字符串 存入session v_code_str = "".join(tmp_list) request.session["v_code"] = v_code_str.upper() # 加干扰线 # width = 250 # 图片宽度(防止越界) # height = 35 # 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_obj.line((x1, y1, x2, y2), fill=get_color()) # # # 加干扰点 # for i in range(2): # draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=get_color()) # x = random.randint(0, width) # y = random.randint(0, height) # draw_obj.arc((x, y, x+4, y+4), 0, 90, fill=get_color()) # 第一版: 将生成的图片保存到文件中 # with open("xx.png", "wb") as f: # img_obj.save(f, "png") # print("图片已经生成!") # with open("xx.png", "rb") as f: # return HttpResponse(data, content_type="image/png") # 第二版 直接将图片保存在内存中 from io import BytesIO tmp = BytesIO() # 生成一个io 对象 img_obj.save(tmp, "png") data = tmp.getvalue() return HttpResponse(data, content_type="image/png")