环境

Windows 10
MongoDB 4.2
Python  3.8
pymongo 3.10.1

bson(小图片)

  • bson 用来存放小于 16MB 的小文件
  • Python 示例代码
#encoding: utf-8
#author: qbit
#date: 2020-05-20
#summary: 用 MongoDB 存放、读取小图片

import pymongo
from bson import binary
def img2mongo(coll: pymongo.collection.Collection, 
            imgId: str,
            imgBuf: bytes):
    r"""
    coll: MongoDB 集合
    imgId: 图片ID
    imgBuf: 图片的二进制 Buffer
    """
    print('img2mongo ...')
    bin = binary.Binary(imgBuf)
    return coll.insert_one({'_id': imgId, 'img_bin': imgBuf})    

def mongo2img(coll: pymongo.collection.Collection, 
            imgId: str):
    r"""
    coll: MongoDB 集合
    imgId: 图片ID
    返回: 图片的二进制文件
    """
    print('mongo2img ...')
    dic = coll.find_one({'_id': imgId})
    return dic['img_bin']
if __name__ == "__main__":
    username = 'xxx'
    password = 'xxx'
    host = '192.168.1.72'
    port = 27017
    dbname = 'student'
    connStr = f'mongodb://{username}:{password}@{host}:{port}/{dbname}?authSource=admin'
    db = pymongo.MongoClient(connStr).get_database()
    coll = db.img
    coll.drop()
    with open('520_in.jpg', mode='rb') as f:
        inBuf = f.read()
    img2mongo(coll, '520', inBuf)
    outBuf = mongo2img(coll, '520')
    with open('520_out.jpg', mode='wb') as f:
        f.write(outBuf)

GridFS(大图片)

  • GridFS 用来存放大于 16 MB 的大文件
本文出自 qbit snap

qbit
268 声望279 粉丝