我有一个Django应用程序,允许用户上传保存在Azure blob存储中的图像。当用户上传图像时,我想要存储原始图像并创建缩略图(100x100)。
目前,该网站完美地从request.FILES
上传原文,但是为了创建缩略图,我无法弄清楚如何在未先将已编辑的图像保存到保留文件夹的情况下上传到Azure,读取保存的图像,然后删除它。这似乎不是保存缩略图的最有效方法。
以下是当前的上传脚本:
# original upload
f = request.FILES['pic']
extension = f.name.split('.')[-1]
new_name, thumb_name = rename_file(extension)
upload(blob_service, 'pic-container', new_name, f)
# create thumbnail
f.seek(0)
im = Image.open(f)
width = im.size[0]
height = im.size[1]
if width > height:
left_crop = (width - height)/2
right_crop = (width + height)/2
cropped = im.crop((left_crop, 0, right_crop, height))
else:
upper_crop = (height - width)/2
lower_crop = (height + width)/2
cropped = im.crop((0, upper_crop, width, lower_crop))
std_size = 100, 100
cropped.thumbnail(std_size, Image.ANTIALIAS)
# save to holder, upload thumbnail, then delete from holder
cropped.save('path/to/holder/' + thumb_name)
upload(blob_service, 'media-pic', thumb_name, open('path/to/holder/' + thumb_name))
os.unlink('path/to/holder/' + thumb_name)
# upload script slightly modified from http://www.windowsazure.com/en-us/documentation/articles/storage-python-how-to-use-blob-storage/#_large-blobs
def upload(blob_service, container_name, blob_name, file_path):
blob_service.put_blob(container_name, blob_name, '', 'BlockBlob')
block_ids = []
index = 0
with file_path as f:
while True:
data = f.read(chunk_size)
if data:
length = len(data)
block_id = base64.b64encode(str(index))
blob_service.put_block(container_name, blob_name, data, block_id)
block_ids.append(block_id)
index += 1
else:
break
blob_service.put_block_list(container_name, blob_name, block_ids)
如果我不首先保存缩略图而只是运行upload(blob_service, 'pic-container', thumb_name, cropped)
我会收到一个非常无法提供信息的错误,只是说__exit__
并指向with file_path as f
中的行def upload
有没有办法直接从cropped
上传文件而无需保存文件,无论是修改上传功能还是以某种方式更改cropped
。