繁体   English   中英

使用 Gridfs 将 base64 字符串图像存储到 MongoDB

[英]Store base64 string image to MongoDB using Gridfs

我目前正在尝试使用 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 function 的文档,但它所采用的数据类型的确切类型尚不清楚。

“数据可以是 str 的实例(python 3 中的字节)或提供 read() 方法的类似文件的 object。”

如何将 base64 字符串转换为 gridfs 支持的字节?

Gridfs put 方法接受二进制文件。

# 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM