如何使用 python 和 pillow 将图像存储在 mongodb 文档中?
How to store an image in a mongodb document using python and pillow?
我有以下代码可以根据对 url 的请求创建缩略图:
r = requests.get(image_url, stream=True, headers=headers)
size = 500, 500
img = Image.open(r.raw)
thumb = ImageOps.fit(img, size, Image.ANTIALIAS)
此时我想将图像存储在 mongo 文档中,如下所示:
photo = {
'thumbnail': img,
'source': source,
'tags': tags,
'creationDate': datetime.now(),
}
显然这是行不通的,那么我需要应用什么样的转换才能做到这一点?
好的,这是我对此的想法(不过我不确定它是否有效;一些想法来自 here)。
我认为你可以使用 pymongo 库中的 Binary BSON 类型实现你需要的。尝试以二进制加载图像。说使用 PILLOW (pil.image) 或
image_file = open('1.bmp', 'rb')
或
image_file = StringIO(open("test.jpg",'rb').read())
然后将其发送到 Binary(image_file) 输入 pymongo
Binary_image_file = Binary(image_file) #pymongo libary
然后在mongo中正常插入。
阅读。做一个正常的查找()。然后从key中加载值并将存储的数据转换为图像为:
image_data = StringIO.StringIO(Stringio_image_file)
image = Image.open(image_data)
希望对您有所帮助。 (你也可以使用 Aydin base64 命题)。
祝一切顺利。
我有以下代码可以根据对 url 的请求创建缩略图:
r = requests.get(image_url, stream=True, headers=headers)
size = 500, 500
img = Image.open(r.raw)
thumb = ImageOps.fit(img, size, Image.ANTIALIAS)
此时我想将图像存储在 mongo 文档中,如下所示:
photo = {
'thumbnail': img,
'source': source,
'tags': tags,
'creationDate': datetime.now(),
}
显然这是行不通的,那么我需要应用什么样的转换才能做到这一点?
好的,这是我对此的想法(不过我不确定它是否有效;一些想法来自 here)。
我认为你可以使用 pymongo 库中的 Binary BSON 类型实现你需要的。尝试以二进制加载图像。说使用 PILLOW (pil.image) 或
image_file = open('1.bmp', 'rb')
或
image_file = StringIO(open("test.jpg",'rb').read())
然后将其发送到 Binary(image_file) 输入 pymongo
Binary_image_file = Binary(image_file) #pymongo libary
然后在mongo中正常插入。
阅读。做一个正常的查找()。然后从key中加载值并将存储的数据转换为图像为:
image_data = StringIO.StringIO(Stringio_image_file)
image = Image.open(image_data)
希望对您有所帮助。 (你也可以使用 Aydin base64 命题)。
祝一切顺利。