Back to TILs.

Calmcode TIL

Base64 Images logoBase64 Images

There are two images shown below (original found here), but they are hosted differently.

If you have a look at the source code you'll notice that one image is hosted by linking to a file with the other one is hosted as a long base64 string.

Cat
This is an image, hosted with a link.
Cat
This is an image, hosted directly.

The standard way of hosting an image is with a src= reference, like below.

<img src="/static/images/content/til/base64-til-cat.png" alt="Cat">

But you can also directly embed the image by encoding it. That would look more like this:

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAA..." alt="Cat">

The base64 string is usually much (!) longer than the codesnippet suggests, especially if you're sharing a high resolution image. This base64 style might look familiar if you've ever looked at .ipynb files. These base64 encodings allow you to store images as plain text, which also means that you can share them as part of a json file.

Generating Base64

You can generate these base64 strings yourself with Python by leveraging the base64 submodule.

import base64

with open("path/img.png", "rb") as image_file:
    enc_str = base64.b64encode(image_file.read()).decode('utf-8')

The enc_str will contain the encoded string that you can copy in the <img> tag.

<img src="data:image/png;base64, <copy string here>" alt="Cat">

Back to main.