"""
file 文件地址 可以是 request.FILES[''] 格式
path 新格式图片地址
"""
def img_convert(file,path):
import Image
image = Image.open(file)
image.convert('RGB')
image.save(path,image.format)
"""
生成缩略图
file 图片地址 或者 request.FILES['file']
width 缩略图宽
height 缩略图高
path 生成的缩略图的完整文件名(含路径)
"""
def thumbnail(file,width,height,path):
import Image
image = Image.open(file)
image.convert('RGB')
image.thumbnail((width,height),Image.ANTIALIAS)
image.save(path,image.format)
"""
获取文件后缀名 不包含 .
"""
def file_ext(filename):
return os.path.splitext(filename)[1]
"""
返回一个指定后缀的文件完整路径
"""
def get_file_name(ext):
import time,random
from django.conf import settings
file_dir = os.path.join(settings.MEDIA_ROOT,time.strftime('%Y/%m/%d/'))
if not os.path.exists(file_dir):
os.makedirs(file_dir)
file_name = time.strftime('%Y%m%d%H%M%S')
file_name = file_name + '%d' % random.randint(0,100)
return file_dir + file_name + ext
def handle_uploaded_file(file):
ext = file_ext(file.name)
file_name = get_file_name(ext)
#生成缩略图
thumb_file = file_name.replace('.','_s.')
thumbnail(file,120,120,thumb_file)
#上传
destination = open(file_name, 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
return file_name
转载于:https://www.cnblogs.com/quqiufeng/archive/2011/10/28/2227783.html