使用Python从cx_oracle BLOB输出图像

2 投票
2 回答
9197 浏览
提问于 2025-04-17 10:20

我在一个Oracle数据库的表里存储了图片,使用的是BLOB这一列。我之前用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内容。

2 个回答

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

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

撰写回答