filter for simplifying creating data URI´s

 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. [UPDATE]Filter to resize a ImageField on demand by rafacdb 5 years, 8 months ago
  2. Auto Generate/Save Thumbnails using Template Filter (scale max_x, max_y, or both) by ThisbeTom 5 years, 4 months ago
  3. Filter to generate QR codes by javinievas 3 years, 8 months ago
  4. Filter to resize a ImageField on demand by michelts 6 years, 12 months ago
  5. iPernity thumbnail helper by sedden 5 years, 5 months ago

Comments

(Forgotten your password?)