2012-01-16 75 views
2

我已經將圖像存儲在BLOB列中的oracle表中。我用來讀取和輸出圖像並使用JAVA寫入數據。我想用Python做同樣的事情(獲取我的圖像並分發它)。我正在使用Flask框架和cx_Oracle。使用python從cx_oracle blob輸出圖像

我設法讓我的BLOB內容進入我的應用程序,但我不知道如何從中生成圖像。

我知道,在的Java我用:

OutputStream out = response.getOutputStream(); 
response.setContentType(doc.getContentType()); 
IOUtils.copy(new ByteArrayInputStream(doc.getContent()),out); 
out.flush(); 

其中doc.getContent()是我的BLOB的內容。

回答

2

如果你有這些數據,只需要將它獲取到磁盤上的圖像文件,你可以直接寫入打開的文件以二進制模式寫入。

import cx_oracle 

sql = 'select img_fld from img_table where id=1234' 
imagePath = './output/image.png' 

conn = cx_oracle.connect('your_connection_string') 

cursor = conn.cursor() 
cursor.execute(sql) 

#assuming one row of image data is returned 
row = cursor.fetchone() 
imageBlob = row[0] 

#open a new file in binary mode 
imageFile = open(imagePath,'wb') 

#write the data to the file 
imageFile.write(imageBlob.read()) 

#closing the file flushes it to disk 
imageFile.close() 

cursor.close() 
conn.close() 

如果你需要一個「類文件」對象,而在寫入磁盤可以使用cStringIO模塊創建內存緩衝區。 https://docs.python.org/library/stringio.html

+0

IG遇到錯誤'imageFile.write(imageBlob)'' 類型錯誤:必須是字符串或緩衝區,而不是cx_Oracle.LOB' – asdfme123 2015-03-12 05:15:37

+0

@ asdfme123你已經錯過了' .read()'。改爲使用'imageFile.write(imageBlob.read())'。 – mtoloo 2016-10-13 11:54:17

2

使用瓶和您的幫助:

@app.route('/_photo/') 
def gripur(): 

    conn = cx_Oracle.connect("*****","****",make_dsn_tns(get_config_string())) 
    curs = conn.cursor() 
    #find photo 
    document=curs.execute('select myblob from mytable where id=34234') 
    row = cursor.fetchone() 
    imageBlob = row[0] 

    blob= imageBlob.read() 
    response = make_response(blob) 
    response.headers["Content-type"] = "image/jpeg" 
    conn.close() 

    return response