代码之家  ›  专栏  ›  技术社区  ›  user9503597

无法在模板上呈现PIL对象base64图像

  •  3
  • user9503597  · 技术社区  · 7 年前

    我试图在转换为base64后显示一个PIL对象。 我在src标记中获得base64值,但即使在解码后也不会呈现响应

    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

    我们将非常感谢您的帮助。

    1 回复  |  直到 7 年前
        1
  •  5
  •   Fariborz Ghavamian Rishabh Tariyal    6 年前

    b64encode(buffered.getvalue())返回字节类对象。在将其传递给模板之前,需要将其转换为字符串。可按如下方式进行:

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