Snippets

Sergey Prymak Django template tag converting a stream to data URI

Created by Sergey Prymak
@register.filter()
def data_uri(stream):
    mime_type, unused = mimetypes.guess_type(stream.name)
    if mime_type is None:
        mime_type = 'application/octet-stream'
    result = 'data:%s;base64,' % mime_type
    if hasattr(stream, 'read') and callable(stream.read):
        value = stream.read()
        s = b64encode(force_bytes(value)).decode('ascii')
        return result + s.replace("\n", "")
    return ''
    {% thumbnail organization.business_profile.logo 130x130 as thumb %}
    <table cellpadding="0" cellspacing="0">
        <tr align="top">
            <td valign="top" width="150px">
                {% if thumb.file %}
                <img class="logo"
                    {% if media == 'print' %}src="{{ thumb.file.file|data_uri }}"{% else %}src="{{ thumb.url }}"{% endif %}
                >
                {% endif %}
            </td>
            <td valign="top">
                <h1>Lorem Ipsum<br>
                    <small>www.example.com</small>
                </h1>
            </td>
        </tr>
    </table>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.