python flask将读取的图片返回给web前端

网上找到的python代码(核心部分):

def return_img_stream(img_local_path):
    """
    工具函数:
    获取本地图片流
    :param img_local_path:文件单张图片的本地绝对路径
    :return: 图片流
    """
    import base64
    img_stream = ''
    with open(img_local_path, 'r') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream)
    return img_stream
 
@app.route('/')
def hello_world():
    img_path = '/home/hogan/Googlelogo.png'
    img_stream = return_img_stream(img_path)
    return render_template('index.html',
                           img_stream=img_stream)

html 部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask Show Image</title>
</head>
<body>
    <img style="width:180px" src="data:;base64,{{ img_stream }}">
</body>
</html>

运行后发现,图片显示有问题
网页一直是这个样子:
在这里插入图片描述
原因找了好久,其中

open(img_local_path, 'r') 

要将’r’改为’rb’
然后最关键的是:
将这句后加上.decode()

img_stream = base64.b64encode(img_stream).decode()

就可以正常显示图片了
在这里插入图片描述
参考博客:
python str与bytes之间的转换
python的flask框架实现将python绘制的图像显示到web页面
python Flask中返回图片流给前端展示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章