Django: How to send image file as part of response

Using Base64 might be useful in some scenarios.

Published: May 10, 2020
App Store

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:

<img src="data:image/png;base64,{{ image }}">

And that is it 🙂

Thanks for reading!

Bluesky logo

Follow on Bluesky to not miss new posts

Filip Němeček profile photo

WRITTEN BY

Filip Němeček Mastodon

iOS blogger and developer with interest in Python/Django.

iOS blogger and developer with interest in Python/Django.