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/