Login

Image as base64 in django

Author:
agusmakmun
Posted:
August 4, 2017
Language:
Python
Version:
Not specified
Tags:
django image base64
Score:
0 (after 0 ratings)

Easy way to get base64 for the image to display in the template, eg: <img src="{{ post.get_cover_base64 }}">

 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
29
import os
import base64

def image_as_base64(image_file, format='png'):
    """
    :param `image_file` for the complete path of image.
    :param `format` is format for image, eg: `png` or `jpg`.
    """
    if not os.path.isfile(image_file):
        return None
    
    encoded_string = ''
    with open(image_file, 'rb') as img_f:
        encoded_string = base64.b64encode(img_f.read())
    return 'data:image/%s;base64,%s' % (format, encoded_string)


# Example Usage

from django import models
from django.conf import settings

class Post(models.Model):
    ...
    cover = models.ImageField(upload_to='images/%Y/%m/%d')
    
    def get_cover_base64(self):
        # settings.MEDIA_ROOT = '/path/to/env/projectname/media'
        return image_as_base64(settings.MEDIA_ROOT + self.cover.path)

More like this

Comments

Please login first before commenting.