python - 在 HTML 页面上显示图像而不保存到磁盘
问题描述
我想从文件夹中加载图像对其进行一些处理,然后将其显示在 HTML 页面上,而不存储在磁盘上。我关注了这篇讨论类似问题但图像未显示的帖子
这是我正在使用的代码
应用程序.py
from flask import Flask, render_template
from base64 import b64encode
import cv2 as cv
import os
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
target = os.path.join(APP_ROOT, 'static')
@app.route("/")
def index():
uri1 = ''
return render_template("output.html", uri1=uri1)
@app.route("/img_prcoess", methods=['POST'])
def img_prcoess():
# Read the image
src_img = cv.imread("/".join([target, 'bradley_cooper.jpg']))
# Convert image to Gray
img1_gray = cv.cvtColor(src_img, cv.COLOR_BGR2GRAY)
# Encode
uri1 = "data:%s;base64,%s" % ("image/jpeg", b64encode(img1_gray))
return render_template("output.html", uri1=uri1)
if __name__ == "__main__":
app.run(port=4444, debug=True)
输出.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="form1" action="{{ url_for('img_prcoess') }}" method="POST" enctype="multipart/form-data">
<input type="submit" value="Show Image" id="button1" width="100px">
</form>
<img style="height: 300px" src="{{ uri1 }}">
</body>
目录结构
解决方案
您无法将图像的原始数据转换为数据 url。您必须先更改格式。
@app.route('/process', methods=['POST'])
def process():
path = os.path.join(APP_ROOT, 'static', 'example.jpg')
srcimg = cv.imread(path)
dstimg = cv.cvtColor(srcimg, cv.COLOR_BGR2GRAY)
retval, buffer = cv.imencode('.jpg', dstimg)
uri = "data:%s;base64,%s" % ('image/jpeg', b64encode(buffer).decode('ascii'))
return render_template('process.html', **locals())
推荐阅读
- r - 如何打破键值并存储在两个不同的变量中,以将它们用作 r 和闪亮的 ms SQL server 中的参数(stored_procedure)
- angular - 在单独的应用程序中托管时编译构建的角度元素的源映射
- excel - 如何使用VBA检测Excel中的图表中是否有文本框?
- typescript - 即使文件被排除在外,来自 tsc 的警告
- twitter-bootstrap - 从 bootstrap-vue scss 扩展
- arrays - 使用 $dateFromString 将 MongoDB 中数组中的字符串转换为日期格式(存在 NaT)
- python - python如何在数组中的峰值点之后放置递减的指数元素?
- python - Django SplitDateTime 小部件抛出“list”对象没有属性“strip”
- javascript - ngx-image-cropper IE-11 不工作 Angular 7.2
- javascript - 在 javascript 中添加大十进制值以计算谷歌地图上的距离