python - 如何从发布的 base64 编码图像创建 MongoDB/mongoengine ImageField?

标签 python mongodb python-imaging-library mongoengine imagefield

我有一个小型 Python/Flask 应用程序,它应该在 MongoDB 中存储图片。

  1. 客户端提交一个 HTTP POST (JSON),其中一个字段是 base64 编码的图像。
  2. 服务器应将此图像存储在 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/

相关文章:

python - 设置 mac osx lion 的 eclipse ee 首选项

python - 将 Flask 更改应用到 Apache2 服务器而不重新启动

python - 将图边列表转换为 JSON 树

python - 如何在python中绘制一个可以指示鼠标移动到图形某个部分时的值的图形并将其放在网页上?

java - Spring MVC MongoDB 配置

mysql - 存储具有不同属性的实体(EAV 替代方案)

python图像库无法将PNG保存为JPG

node.js - 在compoundjs初始化期间如何从jugglingdb适配器获取 native mongodb客户端?

python - 捕获图像进行处理

python - 使用 pytesser 识别简单数字