This filter will return data URI for given file, for more info go to: wikipedia
Sample Usage:
<img src="{{ "/home/visgean/index.png"|dataURI }}">
will be filtered into:
<img src="data:image/png;base64,iVBORw0...">
This is good for small images.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | # -*- 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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.