Created
August 18, 2011 00:38
-
-
Save Visgean/1153019 to your computer and use it in GitHub Desktop.
simple filter for simplifying creating data URI´s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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