Showing an image on an HTML page without saving to disk

I want to load an image from the folder do some processing on it and then show it on the HTML page without storing on the disk. I followed this post which discusses similar problem but image is not showing

Here is the code I am using

app.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)

output.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>

Directory Structure

enter image description here

Answer

You cannot convert the raw data of the image into a data url. You have to change the format first.

@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())