Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Flask, display an image stored as a binary blob in MySQL database

I’m trying to display an image that is stored in a LONGBLOB column in a MySQL database, using Flask:

app.py:

@app.route('/get_image', methods=['GET'])
def get_image():
    args = request.args
    image_id = args.get('image_id')

    image = # code for getting image blob from database
    return send_file(image, mimetype='image/png')

HTML code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<img src="http://127.0.0.1:5000/get_image?image_id=1"/>

When a request for the image is sent, I can see in debugger that the image bytes are retrieved from the database:

enter image description here

However the image is not displayed:

enter image description here

>Solution :

The send_file function expects a path-like or file-like object, not a bytes object. Use BytesIO to give your bytes a file-like interface:

from io import BytesIO

@app.route('/get_image', methods=['GET'])
def get_image():
    args = request.args
    image_id = args.get('image_id')

    image = # code for getting image blob from database

    #                   👇🏿
    return send_file(BytesIO(image), mimetype='image/png')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading