1

flask code:

from base64 import b64encode
def abc()
    encoded = b64encode(img_data)
    mime = "image/jpeg"
    uri = "data:%s;base64,%s" % (mime, encoded)

    return render_template('/result.html',uri=uri)

html code:

<img src="{{ uri }}">

I tried this, but the image is not getting displayed. Any idea how? I have image in a numpy array.

john doe
  • 151
  • 1
  • 10

3 Answers3

4

Solution:

file_object = io.BytesIO()
img= Image.fromarray(originalimg.astype('uint8'))
img.save(file_object, 'PNG')
base64img = "data:image/png;base64,"+b64encode(file_object.getvalue()).decode('ascii')

HTML:

<img src="{{base64img}}"      >
john doe
  • 151
  • 1
  • 10
1

this is just the complementary solution for the above solution, I was searching for this for like 12 hours, thanks @john_doe, here is my solution combined with the above solution I hope it also helps someone:

def upload_file():
   if request.method == 'POST':
        f = request.files['file'].read()
        #    print(f)
        npimg = np.fromstring(f,np.uint8)
        img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
        img = Image.fromarray(img.astype("uint8"))
        rawBytes = io.BytesIO()
        img.save(rawBytes, "JPEG")
        rawBytes.seek(0)
        img_base64 = base64.b64encode(rawBytes.getvalue()).decode('ascii')
        mime = "image/jpeg"
        uri = "data:%s;base64,%s"%(mime, img_base64)
        return render_template("./template/output.html",image=uri)
sameer maurya
  • 111
  • 1
  • 4
-1

This is a complementary solution to the one above of sameer maurya,

The python code:

import io
import numpy as np
from PIL import Image
import base64

def render_frame(arr: np.ndarray):
    mem_bytes = io.BytesIO()
    img = Image.fromarray(arr)
    img.save(mem_bytes, 'JPEG')
    mem_bytes.seek(0)
    img_base64 = base64.b64encode(mem_bytes.getvalue()).decode('ascii')
    mime = "image/jpeg"
    uri = "data:%s;base64,%s"%(mime, img_base64)
    return render_template("main.html", image=uri)

NP_IMAGE = (np.random.random((300,400, 3)) * 255).astype("uint8")

@app.route("/", methods=['GET'])
def main():
    return render_frame(NP_IMAGE)


the html code:

<img src="{{ image }}">
Matesanz
  • 19
  • 5