如何将图像保存到dis

2024-10-01 07:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

I working on a mobile application, where user can upload images, am using Django in server side.

我有两种方法得到图像,我想在例外情况下把图像保存到磁盘上。在

imageFile = request.FILES['image']
try:
    file_path = imageFile.temporary_file_path()
except AttributeError as e:
    logger.debug(virtualFile')
    imageStringBuffer = imageFile.read()
    virtualFile = StringIO.StringIO(imageStringBuffer)
    # want to  save the  imageStringBuffer to disk

I want to to save the 'virtualFile' (in except case) to the disk , How can I do it?


Tags: thetopathin图像savecanfile
3条回答

这将使用请求库来获取图像,打开/创建测试.png把内容写进去。在

import requests
resp = requests.get('url-to-image')
f = open('test.png','w')
f.write(resp.content)
def handle_uploaded_file(f):
    with open('imgepath', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

参考:here

您不需要virtualFile。您已经在imageStringBugger中拥有图像数据。因此:

with file('filename_to_save_to.png', 'wb') as f:
    f.write(imageStringBuffer)

够了。在

相关问题 更多 >