def create_new_thumb(media_path, instance, owner_slug, max_length, max_width):
filename = os.path.basename(media_path)
thumb = Image.open(media_path)
size = (max_length, max_width)
thumb.thumbnail(size, Image.ANTIALIAS)
temp_loc = "%s/%s/tmp" %(settings.MEDIA_ROOT, owner_slug)
if not os.path.exists(temp_loc):
os.makedirs(temp_loc)
temp_file_path = os.path.join(temp_loc, filename)
if os.path.exists(temp_file_path):
temp_path = os.path.join(temp_loc, "%s" %(random.random()))
os.makedirs(temp_path)
temp_file_path = os.path.join(temp_path, filename)
temp_image = open(temp_file_path, "w")
thumb.save(temp_image)
thumb_data = open(temp_file_path, "r")
thumb_file = File(thumb_data)
instance.media.save(filename, thumb_file)
shutil.rmtree(temp_loc, ignore_errors=True)
return True
评论列表
文章目录