开启用户验证下的gridfs 连接使用,在执行脚本前可以在python shell中

from pymongo import Connection
from gridfs import *
con = Connection("mongodb://admin:admin@127.0.0.1:27017")#用URI的方式建立数据库的链接,当然也有其他的方式进行授权,现在是mongodb的管理员帐号,普通帐号不知道为什么不可以,
db = con['repository']#连接到具体的数据库
fs = gridfs.GridFS(db, 'images')#连接到collection,不存在的话会进行创建
fs.put('data.txt')
ObjectId('50b8176989ee3209bccb0b542881064151')#shell 返回文件在mongodb中的id,此时该数据库中会新建两个集合,images.chunk 和images.files
其中关于ObjectId的导入问题
在pymongo 2.2版本一下需要从pymongo.objectid中导入
在2.2及以上版本中从bson.objectid 中导入
Python 脚本如下
__author__ = 'jiangyt'
#encoding=utf-8
from pymongo import Connection
from gridfs import *
from PIL import Image
from bson.objectid import ObjectId
import StringIO
import threading, time
#文件处理系统
class GFS:
#定义connection and fs
c = None
db = None
fs = None
instance = None
locker = threading.Lock()
@staticmethod
def _connect():
if not GFS.c:
GFS.c = Connection( "mongodb://admin:admin@127.0.0.1:27017") # 建立mongodb的连接
GFS.db = GFS.c['maidiansha'] #连接到指定的数据库中
GFS.fs = GridFS(GFS.db, collection='images') #连接到具体的collection中
#初始化
def __init__(self):
print "__init__"
GFS._connect()
print "server info " + " * " * 40
print GFS.c.server_info
#获得单列对象
@staticmethod
def getInstance():
GFS.locker.acquire()
try:
GFS.instance
if not GFS.instance:
GFS.instance = GFS()
return GFS.instance
finally:
GFS.locker.release()
#写入
def put(self, name, format="png",mime="image"):
gf = None
data = None
try:
data = StringIO.StringIO()
name = "%s.%s" % (name,format)
image = Image.open(name)
image.save(data,format)
#print "name is %s=======data is %s" % (name, data.getvalue())
gf = GFS.fs.put(data.getvalue(), filename=name, format=format)
except Exception as e:
print "Exception ==>> %s " % e
finally:
GFS.c = None
GFS._connect()
return gf
#获得图片
def get(self,id):
gf = None
try:
gf = GFS.fs.get(ObjectId(id))
im = gf.read() #read the data in the GridFS
dic = {}
dic["chunk_size"] = gf.chunk_size
dic["metadata"] = gf.metadata
dic["length"] = gf.length
dic["upload_date"] = gf.upload_date
dic["name"] = gf.name
dic["content_type"] = gf.content_type
dic["format"] = gf.format
return (im , dic)
except Exception,e:
print e
return (None,None)
finally:
if gf:
gf.close()
#将gridFS中的图片文件写入硬盘
def write_2_disk(self, data, dic):
name = "./get_%s" % dic['name']
if name:
output = open(name, 'wb')
output.write(data)
output.close()
print "fetch image ok!"
#获得文件列表
def list(self):
return GFS.fs.list()
#删除文件
def remove(self,name):
GFS.fs.remove(name)
if __name__== '__main__':
image_name= raw_input("input the image name>>")
if image_name: www.codesec.net
gfs = GFS.getInstance()
if gfs:
image_id = gfs.put(image_name)
print "==========Object id is %s and it's type is %s==========" % (image_id , type(image_id))
(data, dic) = gfs.get(ObjectId(image_id))
gfs.write_2_disk(data, dic)

将gridFS中的图片文件写入硬盘的更多相关文章

  1. WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片

    原文:WPF中实现图片文件转换成Visual对象,Viewport3D对象转换成图片 1.图片文件转换成Visual对象 private Visual CreateVisual(string imag ...

  2. Aspose.Words提取word文档中的图片文件

    /// <summary> /// 提取word中的图片 /// </summary> /// <param name="filePath">w ...

  3. mongodb中获取图片文件<标记>

    获取图片文件 @RequestMapping(value="/downLoadFileFormMongo.do",method=RequestMethod.GET) @Respon ...

  4. linux下,将一个目录中的图片文件合成为gif图片

    # {} 为文件所在目录位置 # {} 为gif图片位置 convert -delay -depth -layers optimize -quality -loop {} {}

  5. Java中对图片文件的类型的获取

    public static void main(String[] args) {        File f = new File("c://test.jpg");         ...

  6. 将raw里面的数据库文件写入到data中

    package com.city.list.db; import java.io.File; import java.io.FileNotFoundException; import java.io. ...

  7. [转] 从数据库中读取图片并导入Excel文件,C#方式

    原文地址, 作者 Lvyou1980 直接源码吧. using System; using System.IO; using System.Data; using System.Drawing; us ...

  8. 利用FlashPaper在web页面中显示PDF文件(兼容各浏览器)

    应项目需求要把PDF内嵌到网页中显示,其中有了很多办法,比如用<embed/>元素放入PDF文件,但是效果不理想,浏览器兼容不理想,在ie9/8(其他版本没有测试)显示会提示下载pdf文件 ...

  9. Java中显示图片的方法

    最近在做一个swing小项目,其中需要把存储在硬盘中的图片文件显示出来,总结了如下方法: 1. Graphics g = getGraphics();String name = "E:/Ca ...

随机推荐

  1. 记录java基础的学习过程

    标识符(类名:变量.属性.方法名: ) 组成:类名开头不能是数字,只能有字母数字_$组成. 命名规范: 类名每一个单词首字母大写(HelloWorld大驼峰法则), 方法名 属性名 变量名首字母小写之 ...

  2. js:方法3. 对象

    Object.constructor object.constructor a = new Array(1,2,3); // Create an object a.constructor == Arr ...

  3. css3 -- 伪类与伪元素

    伪类: 1.结构伪类 A:E : first-child{} E : nth-*(n){} E : first-*(even){}  E : first-*(odd){} B:nth-child 是根 ...

  4. CSS3-网站导航,transform,transition

    网站导航: 1.a:link    visited    hover   active的顺序是很重要的,如果改变顺序,则hover以及active的状态不起作用 2.<a href=" ...

  5. Floyd_Warshall POJ 1847 Tram

    题目传送门 题意:这题题目难懂.问题是A到B最少要转换几次城市.告诉每个城市相连的关系图,默认与第一个之间相连,就是不用转换,其余都要转换. 分析:把第一个城市权值设为0, 其余设为0.然后Floyd ...

  6. 疯狂java学习笔记之面向对象(三) - 方法所属性和值传递

    方法的所属性: 从语法的角度来看:方法必须定义在类中 方法要么属于类本身(static修饰),要么属于实例 -- 到底是属于类还是属于对象? 有无static修饰 调用方法时:必须有主调对象(主语,调 ...

  7. iOS学习20之UIView

    1. UI编程概述 UI的本意是用户界面,是英文 User 和 Interface 的缩写. UI设计则是指对软件的人机交互.操作逻辑.界面美观的整体设计. 好的UI设计不仅是让软件变得有个性有品位, ...

  8. 页面显示(pageshow)和页面隐藏(pagehide)事件

    Firefox和Opera有一个新特性,名叫“往返缓存”(back-forward cache,或bfcache),可以在用户使用浏览器的“后退”和“前进”按钮时加快页面的转换速度.这个缓存中不仅保存 ...

  9. Posterior visual bounds retrieval for the Plato framework

    Plato is a MVVM compliant 2D on-canvas graphics framework I've been designing and implementing for d ...

  10. Android ftp 上传图片

    1.确定ftp文件夹 /** FTP文件夹 **/ private String ftpPath = "hshscrenncap" + "/" + DateUt ...