将Flask的request.files属性中的图像加载到PIL图像中

mat*_*ewk 3 python python-imaging-library flask

image = Image.open(request.files["fullimage"])
Run Code Online (Sandbox Code Playgroud)

返回:

IOError:无法识别图像文件

image = Image.open(request.files["fullimage"].read())
Run Code Online (Sandbox Code Playgroud)

返回:

IOError:[Errno 22]无效模式('rb')或文件名:''

请问正确的方法是什么?

小智 8

这可能有效。

img = Image.open(request.files['file'].stream)

也许为时已晚,但希望对其他人有所帮助。


mat*_*ewk 0

我知道会发生这种情况:在尝试组合一个简单的测试用例时,我发现了问题并修复了它。它失败了,因为在尝试将其加载到图像中的行之前,我正在做其他事情,包括:

request.files["fullimage"].read()
Run Code Online (Sandbox Code Playgroud)

没有它,它工作得很好。添加:

request.files["fullimage"].seek(0)
Run Code Online (Sandbox Code Playgroud)

在那一行和将其加载到图像中的行之间解决了问题。我的意思是,我现在有另一个问题,但我会单独发布;-)

  • 您只能从“request.files”读取“文件”**一次**。它是一个流,所以当你读它的时候,你就会清空它。`seek(0)` 不会帮助你。 (2认同)
  • @matthewk:当然,将其写入“StringIO”/“cStringIO”对象中。 (2认同)