mongodb - 如何通过pymongo在MongoDB中存储图像?

标签 mongodb python-3.x opencv binary pymongo

from PIL import Image
from bson import Binary

img = Image.open('test.jpg')
img = Binary(img)

引发错误,指出TypeError : data must be an instance of bytes
为什么会这样?以及如何解决将img存储到MongoDB的问题?

最佳答案

您需要将图像转换为Byte数组。您可以按照以下步骤进行操作,

from PIL import Image
from bson import Binary

img = Image.open('test.jpg')

imgByteArr = io.BytesIO()
img.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()

您可以尝试将imgByteArr保存到mongo中



您可以将图像转换为字符串,然后将其存储在mongo中:
import base64

with open("test.jpg", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    //store str in mongo

取回图像
with open("test2.jpg", "wb") as fimage:
    fimage.write(str.decode('base64'))

关于mongodb - 如何通过pymongo在MongoDB中存储图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47668507/

相关文章:

C++ 指针和数组

python - 在 Python 中将带有数组的嵌套 JSON 转换为 DataFrame

python - 使用 Python 3 的 FTP 文本文件为空

javascript - 如何使用 mongodb 将字典推送到嵌套数组?

java - 如何在Spring Data MongoDB中的ProjectionOperation中投影map和reduce?

python-3.x - 谷歌云 : Choosing the right storage option

java - 如何加载原生库来玩框架

python - 删除视频帧的边框/边距

mongodb - 如何在更新大型集合时禁用 mongodb 索引

mongodb - 在列表中显示mongo中的相应字段