1

I am using this block of code to send an image from python to display in HTML.

x = cv2.imread(file)
x = cv2.cvtColor(x, cv2.COLOR_RGB2BGR)
img = io.BytesIO()
x = Image.fromarray(x, 'RGB')
x.save(img, 'PNG')
img.seek(0)
array.append(base64.b64encode(img.getvalue()))
k= k+1
id.append(k)

render_template('html_page.html', data=zip(array,id))

Code to display in HTML page:

{%for i,j in data%}
          <img for="id{{i}}" style = "float:left; width: 180px;" src="data:image/PNG;base64,{{ i }}" alt="display_Image">
{% endfor %}

The image is not getting displayed in the browser.

Can anyone point put what I am doing wrong? Trying to learn image processing with Python.

While debugging I am able to see that the image is getting loaded successfully in python function but is not getting displayed in HTML page.

1 Answer 1

1

Problem is because base64 gives bytes and later template adds prefix b when it converts bytes to string. You have to manually decode() bytes to string.

base64.b64encode(img_io.getvalue()).decode()

BTW: If you have PNG files then you can do the same without cv2, PIL and io

data = open('image.png', 'rb').read()
image = base64.b64encode(data).decode()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.