How to Embed Images as Base64 Strings in Hugo

You can configure your Hugo website to automatically embed an image into a web page as a Base64 string; this post shows you how.

Let’s assume your Markdown posts have this structure:

---
title: 'Some Title'
author: 'Jane Smith'
excerpt: 'Blah blah…'
slug: some-title
image: some-title.jpg
---

This is my article…

Then in your Hugo theme templates you can use code like this to read the image, transform it as Base64, and embed the result on the final HTML:

{{- $imgPath := $page.Params.image -}}
{{- $image := $page.Resources.GetMatch $imgPath -}}
{{- if $image -}}
{{- $thumb := $image.Fit "420x420" -}} {{/* Obviously optional */}}
{{- $base64 := $thumb.Content | base64Encode -}}
  <p><a href="{{ $page.Permalink }}"><img class="thumbnail"
    src="data:{{ $image.MediaType.Type }};base64,{{ $base64 }}"></a></p>
{{- else -}}
  <p><a href="{{ $page.Permalink }}">
    {{ partial "gray-image-placeholder" (dict "className" "thumbnail") }}</a>
  </p>
{{- end -}}

The gray-image-placeholder shown in the else clause is just a file located in the layouts/partials/ folder of your theme, to be used in case the image your specified does not exist, called gray-image-placeholder.html and looking like this:

<img class="{{ .className }}" src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAABAAAAAMACAIAAAA12IJaAAAABGdBTUEAALGPC/
xhBQAAAAFzUkdCAdnJLH8AAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgA
ABdwnLpRPAAAAAlwSFlzAAALEwAACxMBAJqcGAAADS1JREFUeNrt10ENAAAIxDBA9cnHBg
mthP3WSQoAAPhhJAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAA
ABgAAADAAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABg (… snip…)
AAAYAAAAMAAAAAABgAAADAAAACAAQAAAK5bhvYHaF3qNu4AAAAASUVORK5CYII=">

The className inserted will be the one passed in the (dict) used when calling the partial.