首页 > 解决方案 > 在 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>

目录结构

在此处输入图像描述

标签: pythonhtmlflask

解决方案


您无法将图像的原始数据转换为数据 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())

推荐阅读