網上找到的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中返回圖片流給前端展示