from PIL import Image
from bson import Binary
img = Image.open('test.jpg')
img = Binary(img)
会抛出一个错误,错误信息为TypeError : data must be an instance of bytes
为什么会出现这个错误?如何解决并将图像存储到MongoDB中?
from PIL import Image
from bson import Binary
img = Image.open('test.jpg')
img = Binary(img)
会抛出一个错误,错误信息为TypeError : data must be an instance of bytes
为什么会出现这个错误?如何解决并将图像存储到MongoDB中?
from pymongo import MongoClient
from PIL import Image
import io
client = MongoClient()
db = client.testdb
images = db.images
im = Image.open("./image.jpg")
image_bytes = io.BytesIO()
im.save(image_bytes, format='JPEG')
image = {
'data': image_bytes.getvalue()
}
image_id = images.insert_one(image).inserted_id
read_image.py
from pymongo import MongoClient
from bson.binary import Binary
from PIL import Image
import io
import matplotlib.pyplot as plt
client = MongoClient()
db = client.testdb
images = db.images
image = images.find_one()
pil_img = Image.open(io.BytesIO(image['data']))
plt.imshow(pil_img)
plt.show()
from PIL import Image
from bson import Binary
img = Image.open('test.jpg')
imgByteArr = io.BytesIO()
img.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
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'))