[英]How to Create a MongoDB/mongoengine ImageField from POSTed base64-encoded image?
I have a small Python/Flask application that should store a picture in MongoDB. 我有一个小的Python / Flask应用程序,该应用程序应该在MongoDB中存储图片。
The Model: 该模型:
class Image(db.EmbeddedDocument):
data = db.ImageField()
Right now, the relevant server code looks like this: 现在,相关的服务器代码如下所示:
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()
This gives me the error #=>ValidationError: ValidationError (Location:53e37ed6844de403e0998182) (image.grid_id: ['images']) 这给了我错误#=> ValidationError:ValidationError(Location:53e37ed6844de403e0998182)(image.grid_id:['images'])
When I change the assignment of the image data to this: 当我将图像数据的分配更改为此时:
img.data.put(PILImage)
I get the error: #=> ValidationError: Invalid image: read 我收到错误:#=> ValidationError:图片无效:已读
So I thought it perhaps is looking for an object that supports a 'read' method. 因此,我认为它可能正在寻找支持“读取”方法的对象。 When I change the assignment to this: 当我将作业更改为此时:
img.data.put(file_like)
I get the error: #=> "ValidationError: Invalid image: cannot identify image file " 我收到错误:#=>“ ValidationError:无效的图像:无法识别图像文件”
So, I'm able to base64-encode, json.loads(), POST, json.dumps(), base64decode, and create a PIL image from the data, but I somehow can't get the MongoDB ImageField to accept it as an image. 因此,我能够对base64进行编码,json.loads(),POST,json.dumps(),base64decode,并根据数据创建PIL图像,但是我却无法以某种方式使MongoDB ImageField接受它一个图像。
Can anyone help? 有人可以帮忙吗?
One thing: I found that if I simply write the PILImage to disk and then store it by telling mongoengine to 一件事:我发现如果我只是简单地将PILImage写入磁盘,然后通过告诉mongoengine来存储它,
img.data.put("path/to/image/file")
I can work around this, but I would like to avoid filesystem operations, as the application will experience a fair amount of traffic and we suspect IO will be the first bottleneck. 我可以解决此问题,但我想避免文件系统操作,因为该应用程序将经历大量流量,并且我们怀疑IO将成为第一个瓶颈。
If you still need it, here it is my solution: 如果您仍然需要它,这是我的解决方案:
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()
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.