Login

Read image url as base64

Author:
agusmakmun
Posted:
January 28, 2020
Language:
Python
Version:
Not specified
Tags:
django image templatetags base64 imagepreview
Score:
0 (after 0 ratings)

Read the image url as base64 in django, this snippet usefull if you using the django-easy-pdf to solve this issue https://github.com/nigma/django-easy-pdf/issues/53

Usage example:

<img src="{{ profile.photo.url|read_image_as_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
30
31
32
33
34
35
36
37
38
import os
import base64
import requests

from django import template

register = template.Library()


@register.filter
def read_image_as_base64(image_url):
    """
    :param `image_url` for the complete path of image.
    :param `format` is format for image, eg: `png` or `jpg`.

    >>> from yourapp.templatetags.image_tags import *
    >>>
    >>> read_image_as_base64('http://127.0.0.1:8000/static/images/watermark.png')
    'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgxxxxxxx'
    >>>
    """
    if not image_url:
        return image_url

    try:
        response = requests.get(image_url)
        if response.status_code == 200:
            image_data = response.content
            image_format = os.path.splitext(image_url)[-1].replace('.', '').lower()
            encoded_string = base64.b64encode(image_data).decode('utf-8')

            if image_format in ['jpg', 'jpeg', 'png', 'gif']:
                return 'data:image/%s;base64,%s' % (image_format, encoded_string)

    except Exception as error:
        pass

    return image_url

More like this

  1. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 5 months ago
  2. Crispy Form by sourabhsinha396 6 months ago
  3. ReadOnlySelect by mkoistinen 6 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 7 months, 1 week ago
  5. Django Language Middleware by agusmakmun 7 months, 3 weeks ago

Comments

Please login first before commenting.