Advertisements
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:
<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:
However the image is not displayed:
>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')