我目前正在尝试使用GridFS以base64字符串的形式将图像存储到MongoDB,这是到目前为止我的工作解决方案:
def upload(image_string):
image_data = base64.b64decode(image_string)
image = Image.open(io.BytesIO(image_data))
image.save("foo.jpeg")
with open("foo.jpeg", "rb") as img:
storage = GridFS(mongo.mydb, "fs")
storage.put(img, content_type='image/jpeg')
我想知道是否有一种方法可以直接上载图像而不是将图像另存为文件并再次读取以供Gridfs上载? (Google App Engine不允许文件存储)
我看了Gridfs的put
函数的文档,但是对于它所使用的数据类型的确切类型还不清楚。
“数据可以是str的实例(python 3中的字节),也可以是提供read()方法的类似文件的对象。”
如何将base64字符串转换为gridfs支持的字节?
# encode your image to binary text
with open("unnamed.jpg", "rb") as image:
# read the image as text and convert it to binary
image_string = base64.b64encode(image.read())
# create Gridfs instance
fs = gridfs.GridFS(db)
# add the image to your database
put_image = fs.put(image_string)