2

我已将图像存储在 BLOB 列中的 oracle 表中。我使用 JAVA 读取和输出图像并写入数据。我想用 python 做同样的事情(获取我的图像并分发它)。我正在使用 Flask 框架和 cx_Oracle。

我设法将我的 BLOB 内容放入我的应用程序中,但我不确定如何从中生成图像。

我知道在Java中我使用过:

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

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

4

2 回答 2

2

使用 Flask 和你的帮助:

@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
于 2012-01-17T14:34:19.203 回答
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

于 2012-01-16T05:08:16.320 回答