Login

Read image url as base64

Author:
agusmakmun
Posted:
January 28, 2020
Language:
Python
Version:
Not specified
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. 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, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.