3

I'm trying to display a PIL object after converting to base64. I'm getting the base64 value in the src tag but the response is not rendered even after decoding

import base64
import io
def newrules(request):
pic = con(select.fname)
print(pic)
buffered = io.BytesIO()
pic.save(buffered, "PNG")
img_str = base64.b64encode(buffered.getvalue())
template_code = """
{% load static %}
<!DOCTYPE HTML>
<html>
<body>
{% block pagecontent %}
<div>
<img src="data:image/png;base64,{{ img_str }}">
</div>
<div>
{{ img_str }}
</div>
</body>
{% endblock %}
</html>
"""
template = engines['django'].from_string(template_code)
return HttpResponse(template.render(context={'img_str': img_str}))

HTML souce code

terminal API call responses

Template rendered

Any help will be highly appreciated.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • Possible duplicate of [How do you base-64 encode a PNG image for use in a data-uri in a CSS file?](https://stackoverflow.com/questions/6375942/how-do-you-base-64-encode-a-png-image-for-use-in-a-data-uri-in-a-css-file) – snakecharmerb Mar 25 '18 at 11:12
  • See my Python3 answer in the duplicate - basically you need to do `img_str = base64.b64encode(buffered.getvalue().decode()` to pass a `str` rather than `bytes` to the template engine. – snakecharmerb Mar 25 '18 at 11:14

1 Answers1

5

base64.b64encode(buffered.getvalue()) returns a byte class object. It needs to be converted to a string before passing it to a template. It can be done as follows:

img_str = base64.b64encode(buffered.getvalue()).decode('ascii')

Fariborz Ghavamian
  • 809
  • 2
  • 11
  • 23
Rishabh Tariyal
  • 126
  • 1
  • 4