2

I have stored images in a oracle table within a BLOB column. I use to read and output an image and write data using JAVA. I would like to do the same (getting my image and distributing it) with python. I am using Flask framework and cx_Oracle.

I manage to get my BLOB content into my application but I am not sure how to generate an image from that.

I know that in Java i used :

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

where doc.getContent() is my BLOB content.

2 Answers 2

2

Using Flask and your help :

@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
Sign up to request clarification or add additional context in comments.

Comments

2

If you have the data and just need to get it to an image file on disk you can write it directly to a file opened for writing in binary mode.

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()

If you need a "file-like" object without writing to disk you can use the cStringIO module to create in-memory buffers. https://docs.python.org/library/stringio.html

2 Comments

ig got error imageFile.write(imageBlob) TypeError: must be string or buffer, not cx_Oracle.LOB
@asdfme123 you have missed .read(). Use imageFile.write(imageBlob.read()) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.