我有一个小型 Python/Flask 应用程序,它应该在 MongoDB 中存储图片。
- 客户端提交一个 HTTP POST (JSON),其中一个字段是 base64 编码的图像。
- 服务器应将此图像存储在 MongoDB ImageField 中。我现在正在使用 mongoengine。
模型:
class Image(db.EmbeddedDocument):
data = db.ImageField()
现在,相关的服务器代码如下所示:
import Image as PIL
import base64
import cStringIO # I'm trying to give PIL something that can handle common file operations without having to write to disk
imageData = jsondata['image']
file_like = cStringIO.StringIO(base64.decodestring(imageData))
PILImage = PIL.open(file_like)
# new mongo object
img = Image(name="imagename")
img.data = PILImage # assignment of image data
img.save()
这给了我错误 #=>ValidationError: ValidationError (Location:53e37ed6844de403e0998182) (image.grid_id: ['images'])
当我将图像数据的分配更改为:
img.data.put(PILImage)
我收到错误:#=> ValidationError: Invalid image: read
所以我认为它可能正在寻找一个支持“读取”方法的对象。当我将作业更改为此时:
img.data.put(file_like)
我收到错误:#=>“ValidationError:无效图像:无法识别图像文件”
因此,我能够进行 base64 编码、json.loads()、POST、json.dumps()、base64decode,并根据数据创建 PIL 图像,但我无法将 MongoDB ImageField 获取到接受它作为图像。
有人能帮忙吗?
有一件事:我发现如果我简单地将 PILImage 写入磁盘,然后通过告诉 mongoengine 来存储它
img.data.put("path/to/image/file")
我可以解决这个问题,但我想避免文件系统操作,因为应用程序会遇到相当大的流量,我们怀疑 IO 将是第一个瓶颈。
最佳答案
如果您仍然需要它,这是我的解决方案:
import tempfile
# this can change depending if you send the JSON by url or not
file_like = base64.b64decode(imageData)
bytes_image = bytearray(file_like)
with tempfile.TemporaryFile() as f:
f.write(bytes_image)
f.flush()
f.seek(0)
img.data.put(f)
img.save()
希望对你有帮助
关于python - 如何从发布的 base64 编码图像创建 MongoDB/mongoengine ImageField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25184951/