loading...

Django: How to send image file as part of response

nemecek_f profile image Filip Němeček Updated on ・1 min read

In this short blog post I will show you how to send image from Django and display it on page with a single response.

The trick is to use base64 encoding which can turn your image into string which can then be passed as a part of response.

This can have few benefits, the image being part of response so no additional request to get the image is not needed. You can also prevent users from simply copying the link and sending it to someone. Of course they can always take a screenshot..

Or maybe you have project where you don’t want to deal with configuring STATIC_ROOT and all that serving files with Django requires.

The actual Django part is pretty short:

import base64

with open(image_path, "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode('utf-8')

ctx["image"] = image_data

return render(request, 'index.html', ctx)

Note: The "rb" option stands for "read binary".

Optionally you can add try except to catch FileNotFoundError and react accordingly.

Now we just need to display the content using <img> tag:

Base64 image data in <img> tag

The snippet above was showing my markdown error so hence the screenshot.

And that is it 🙂

Thanks for reading!

Posted on Mar 26 by:

nemecek_f profile

Filip Němeček

@nemecek_f

Primarily iOS developer, I also like Django and Python. And dabble with JavaScript occasionally. Love reading and coffee.

Discussion

markdown guide
 

Interesting I didn't know you can do that.

 

Hi @highcenburg , do you know why the second snippet did not work in the DEV.TO editor? Thanks

 

Hi, you can always open an issue if you feel like there's a bug on the platform
github.com/thepracticaldev/dev.to/...