python gridfs_python 将图片存入mongodb,读取图片,gridfs模块
導(dǎo)入圖片
引入模塊,其中g(shù)ridfs模塊不需要單獨安裝,引入了pymongo即可直接引入
from pymongo import MongoClient
from gridfs import *
import os
#鏈接mongodb
client=MongoClient('localhost',27017)
#取得對應(yīng)的collection
db=client.image
#本地硬盤上的圖片目錄
dirs = 'e:\cs'
#列出目錄下的所有圖片
files = os.listdir(dirs)
#遍歷圖片目錄集合
for file in files:
#圖片的全路徑
filesname = dirs + '\\' + file
#分割,為了存儲圖片文件的格式和名稱
f = file.split('.')
#類似于創(chuàng)建文件
datatmp = open(filesname, 'rb')
#創(chuàng)建寫入流
imgput = GridFS(db)
#將數(shù)據(jù)寫入,文件類型和名稱通過前面的分割得到
insertimg=imgput.put(datatmp,content_type=f[1],filename=f[0])
datatmp.close()
print("js")
創(chuàng)建成功后,會在集合中生成fs.flies和fs.chunks
導(dǎo)出圖片
from pymongo import MongoClient
from gridfs import *
client=MongoClient('localhost',27017)
db=client.image
#給予girdfs模塊來寫出,其中collection為上一步生成的,我不知道怎么該名稱。實際上是由fs.flies和fs.chunks組成
gridFS = GridFS(db, collection="fs")
count=0
for grid_out in gridFS.find():
count+=1
print(count)
data = grid_out.read() # 獲取圖片數(shù)據(jù)
outf = open('cs.jpg','wb')#創(chuàng)建文件
outf.write(data) # 存儲圖片
outf.close()
---------------------
作者:a873054267
總結(jié)
以上是生活随笔為你收集整理的python gridfs_python 将图片存入mongodb,读取图片,gridfs模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 寄存器在哪里_二、汇编之寄存器
- 下一篇: websocket python爬虫_p