Login

filter for simplifying creating data URI´s

Author:
visgean
Posted:
August 18, 2011
Language:
Python
Version:
1.3
Score:
2 (after 2 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.