Python Flask,显示MySQL数据库中存储为二进制blob的图像

egmofgnx  于 2023-05-23  发布在  Python
关注(0)|答案(1)|浏览(202)

我尝试使用Flask显示存储在MySQL数据库中LONGBLOB列中的图像:

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代码

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

当发送图像请求时,我可以在调试器中看到从数据库中检索图像字节:

但图像不显示:

s4n0splo

s4n0splo1#

send_file函数需要一个类似于路径或文件的对象,而不是bytes对象。使用BytesIObytes提供类似文件的界面:

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

相关问题