Skip to content

Instantly share code, notes, and snippets.

@Visgean
Created August 18, 2011 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Visgean/1153019 to your computer and use it in GitHub Desktop.
Save Visgean/1153019 to your computer and use it in GitHub Desktop.
simple filter for simplifying creating data URI´s
# -*- coding: UTF-8 -*-
from django import template
from base64 import b64encode
register = template.Library()
@register.filter
def dataURI(filename, mime = None):
"""
This filter will return data URI for given file, for more info go to:
http://en.wikipedia.org/wiki/Data_URI_scheme
Sample Usage:
<img src="{{ "/home/visgean/index.png"|dataURI }}">
will be filtered into:
<img src="data:image/png;base64,iVBORw0...">
"""
with open(filename, "rb") as file:
data = file.read()
encoded = b64encode(data)
mime = mime + ";" if mime else ";"
return "data:%sbase64,%s" % (mime, encoded)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment