最近做一些数据库调研的工作,目标是实现影像更快的入库、出库、查询,并实现并行访问等操作。
将结果总结成一个mysqlImg类。
关于mongodb的图像存储,参见http://www.cnblogs.com/bigbigtree/p/3242483.html
关于mysql&python的问题和mysql官方链接python的API总结,参见
http://www.cnblogs.com/bigbigtree/p/3246638.html
http://www.cnblogs.com/bigbigtree/archive/2013/08/08/3246718.html
http://www.cnblogs.com/bigbigtree/archive/2013/08/09/3247477.html
http://www.cnblogs.com/bigbigtree/p/3248126.html
mysqlImg代码如下,
1 #coding=UTF-8 2 ''' 3 Created on 2013-8-7 4 5 @author: tree 6 ''' 7 __metaclass__ = type 8 9 import mysql.connector 10 import os 11 import time 12 13 14 class mysqlImg(object): 15 """mysqlImg is a class for inserting image 16 """ 17 def __init__(self): 18 19 self.__filelist=[] 20 self.__config = { 21 'user':'root', 22 'password':'******', 23 'host':'localhost', 24 'database':'imgdb'} 25 26 27 def __dirwalk(self,dir,topdown=True): 28 """traverse the documents of self.__dir and save in self.__filelist 29 """ 30 sum=0 31 self.__filelist.clear() 32 33 for root,dirs,files in os.walk(dir,topdown): 34 for name in files: 35 sum+=1 36 temp=os.path.join(root,name) 37 self.__filelist.append(temp) 38 print(sum) 39 40 41 def insertImg(self,imgpath,dbname=None): 42 """insert images in mysql 43 """ 44 if dbname != None: 45 self.__config['database']=dbname 46 47 self.__dirwalk(imgpath) 48 49 sum=0 50 tStart=time.time() 51 52 self.__cnx=mysql.connector.connect(**self.__config) 53 cur=self.__cnx.cursor() 54 cur.execute("DROP TABLE IF EXISTS pyramid") 55 cur.execute("CREATE TABLE pyramid(IdImg INT(11) PRIMARY KEY AUTO_INCREMENT, 56 NameImg VARCHAR(30), 57 DataImg LONGBLOB NOT NULL)") 58 59 try: 60 for fi in self.__filelist: 61 sum+=1 62 print(sum) 63 myimg = open(fi,'rb') 64 data=myimg.read() 65 66 insertString='INSERT INTO pyramid(NameImg,DataImg) VALUES(%s,%s)' 67 args=(fi,data) 68 cur.execute(insertString,args) 69 myimg.close() 70 finally: 71 tEnd=time.time() 72 print ("It cost %f sec" % (tEnd - tStart)) 73 self.__cnx.commit() 74 self.__cnx.close() 75 76 #get image by filename 77 def getbyname(self,filename,savepath): 78 """get img from mysql by NameImg 79 """ 80 if len(filename) < 1: 81 raise TypeError("filename must not be None") 82 if len(savepath) < 1: 83 raise TypeError("dir must be an string of directory") 84 85 self.__cnx=mysql.connector.connect(**self.__config) 86 cur=self.__cnx.cursor() 87 88 try: 89 selectString="SELECT DataImg FROM pyramid WHERE NameImg = %s" 90 cur.execute(selectString,(filename,)) 91 92 data=cur.fetchone()[0] 93 imgout=open(savepath,'wb') 94 imgout.write(data) 95 finally: 96 self.__cnx.close() 97 imgout.close()