一、图片验证码
方式一:
def get_validCode_img(request): path=os.path.join(settings.BASE_DIR,'static','image','1.jpg') with open(path,'rb') as f: img=f.read() return HttpResponse(img)
二、自定义图片验证码磁盘管理
方式二:
def get_validCode_img(request): from PIL import Image img=Image.new(mode='RGB',size=(120,30),color='green') f=open('validCode.png','wb') img.save(f,'png') with open('validCode.png', 'rb') as f: data=f.read() return HttpResponse(data)
三、自定义图片验证码内存管理
方式三:
def get_validCode_img(request): from io import BytesIO # 内存管理 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color='blue') f = BytesIO() # 文件句柄 img.save(f, 'png') data=f.getvalue() return HttpResponse(data)
四、自定义图片验证码画图
方式四:
def get_validCode_img(request): from io import BytesIO # 内存管理 from PIL import Image,ImageDraw,ImageFont from random import randint,choice color=(randint(0,255),randint(0,255),randint(0,255)) img = Image.new(mode='RGB', size=(120, 30), color=color) draw=ImageDraw.Draw(img,"RGB") font=ImageFont.truetype("static/fonts/kumo.ttf",20) valid_list=[] for i in range(5): random_num=str(randint(0,9)) random_lower=chr(randint(65,90)) # 小写字母 random_upper=chr(randint(97,122)) # 大写字母 random_chr=choice([random_num,random_lower,random_upper]) draw.text([10+i*22,2],random_chr,color=color,font=font) valid_list.append(random_chr) f = BytesIO() # 文件句柄 img.save(f, 'png') data = f.getvalue() valid_str="".join(valid_list) print(valid_str) request.session["keepValidCode"]=valid_str return HttpResponse(data)
字体地址:
https://files.cnblogs.com/files/supery007/blogCMS.rar