1

I have implemented django-photologue and I am trying to return a base64 encoded image from my django view as following:

@api_view(('GET',))
def get_gallery(request, id):
    gallery = Gallery.objects.get(id=id)
    data = []

    for photo in gallery.sample():
        data.append(photo.image_url)
    return Response(data)

for Response(data) I get

["data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAFeCAIAAAD8M3pVAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ\nbWFn --string continues--"] 

notice '\n'in the string

I am trying this (http://codebeautify.org/base64-to-image-converter) converter to see if I get the image back and it fails with the returned response.

If I change it to HttpResponse(data) I get:

data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAFeCAIAAAD8M3pVAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ bWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG --string continuous--

notice '\n' is now gone. This result renders image when I try it in this converter.

What is the correct way of returning such base64 images from Django view? I am using angular2 frontend and I am confused what can be returned so that it can be handled on the frontend to render images.

Thinker
  • 5,326
  • 13
  • 61
  • 137
  • where does `image_url` comes from? this might be useful: http://stackoverflow.com/questions/3715493/encoding-an-image-file-with-base64 – dahrens Nov 18 '16 at 13:05
  • image_url: I modified ImageModel as described here- http://www.codedependant.net/2012/04/13/increase-site-performance-with-django-base64-encod/ – Thinker Nov 18 '16 at 13:16
  • may you try changing the encoding part to `encoded_string = base64.b64encode(image_file.read())` as mentioned in the SO answer? __update__ when thinking this through it does not make a real difference I'm afraid. – dahrens Nov 18 '16 at 13:39
  • This one seems promising. – Thinker Nov 19 '16 at 16:24

1 Answers1

0

This is how I've seen it done:

import mimetypes
from base64 import b64decode, b64encode

def encode_b64(value):
    value.file.seek(0)
    mime_type, encoding = mimetypes.guess_type(value.name)
    if not mime_type:
        mime_type = 'image/png'
    data = value.file.read()
    image_data = bytes(
        'data:' + mime_type + ';base64,', encoding='UTF-8') + b64encode(data)
    return image_data  # or str(image_data, 'utf-8')
denvaar
  • 2,174
  • 2
  • 22
  • 26