小編給大家分享一下MongoDB存儲(chǔ)圖片的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家學(xué)習(xí),希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去學(xué)習(xí)方法吧!
成都創(chuàng)新互聯(lián)公司從2013年成立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元紅安做網(wǎng)站,已為上家服務(wù),為紅安各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
一、GridFS
GridFS將圖片數(shù)據(jù)與圖片屬性數(shù)據(jù)分開(kāi)保存,用chunks來(lái)保存圖片數(shù)據(jù),files保存屬性數(shù)據(jù),一個(gè)圖片file可能對(duì)應(yīng)多個(gè)chunks,每個(gè)chunk的內(nèi)存大小固定(16M),若圖片數(shù)據(jù)大于chunk,則分為多個(gè)chunk保存,用同一個(gè)ObjectID關(guān)聯(lián),下載時(shí)自動(dòng)將多個(gè)chunk合并為圖片數(shù)據(jù)。
上傳
from pymongo import MongoClient from gridfs import * import requests client = MongoClient('127.0.0.1', 27017) #連接mongodb db = client.photo #連接對(duì)應(yīng)數(shù)據(jù)庫(kù) #db.authenticate("username","passowd") fs = GridFS(db, collection="images") #連接collection data = requests.get(dic["photo_url"], timeout=10).content # 確認(rèn)數(shù)據(jù)庫(kù)中不存在此圖片之后再保存 if not fs.find_one({"photo_url":dic["photo_url"]}): fs.put(data, **dic) # 上傳成功后,photo數(shù)據(jù)庫(kù)下出現(xiàn)兩個(gè)collection,分別為: images.files, images.chunks12345678910111213
下載
from pymongo import MongoClient from gridfs import * client = MongoClient('127.0.0.1', 27017) #連接mongodb db = client.photo #連接對(duì)應(yīng)數(shù)據(jù)庫(kù) #db.authenticate("username","passowd") fs = GridFS(db, collection="images") #連接collection num = 1 for grid_out in fs.find(no_cursor_timeout=True): data = grid_out.read() # 獲取圖片數(shù)據(jù) outf = open('/home/%d.jpg'%num,'wb') outf.write(data) #存儲(chǔ)圖片 outf.close() if num%100000 == 0 metadata_file = open("/home/metadata%d.csv"%(num/100000+1), "ab") csv_writer = csv.writer(metadata_file,delimiter='\t') row = [grid_out.photo_title.encode('utf-8'), grid_out.uploadDate, grid_out.upload_date, \ grid_out.longitude, grid_out.latitude, grid_out.width, grid_out.height,\ grid_out.owner_name.encode('utf-8'), grid_out.photo_id, grid_out._id, grid_out.photo_url] csv_writer.writerow(row)12345678910111213141516171819
二、bson二進(jìn)制
這種方法將圖片數(shù)據(jù)作為鍵值對(duì)放入字典與屬性數(shù)據(jù)作為整體存入數(shù)據(jù)庫(kù)中。
上傳代碼如下:
from bson import binary from pymongo import MongoClient client = MongoClient('127.0.0.1', 27017) #連接mongodb db = client.photo #連接對(duì)應(yīng)數(shù)據(jù)庫(kù) image_collection = db.images data = requests.get(dic["photo_url"], timeout=10).content # 確認(rèn)數(shù)據(jù)庫(kù)中不存在此圖片之后再保存 if not image_collection.find_one({"photo_url":dic["photo_url"]}) dic["imagecontent"] = binary.Binary(data) image_collection.insert(dic)1234567891011
以上是mongodb存儲(chǔ)圖片的方法的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!