Optimize image hosting with Hugo

Posted: | Updated: | Tags: til webdev

I host all my images outside of Hugo to prevent any large files from residing in my git repository. This has led me to serve high resolution images in most of my posts which aren’t ideal for the end user. I recently learned about Hugos ability to get remote images, aptly titled resources.GetRemote, which then allows me to apply Hugo’s image rendering capabilities.

This video by Eric Murphy covers some compressing and resizing methods within Hugo that I’ve applied to this blog. A detailed list of all the processing options can be found in the Hugo documentation.

The home page

After some quick changes, all featured images fetched on the home page are now resized to 620 pixels with a default quality value of 75. This has reduced my total home page size from 15.6MB to 389KB. I pass the image url and alt text through parameter variables at the top of the post, .Params.media and .Params.media_alt respectively.

Here is an example of the page parameters on a post:

---
title: "NS Sprinters: SGM"
date: 2023-08-05 11:27:00
category: notes
tags:
    - train
media: https://file.pesky.moe/SGM-00.jpg
media_alt: SGM number 2133 at the Railway Museum at Utrecht in its yellow, blue and white livery.
---

This is the snippet of code used in the theme to fetch and process the image.

{{ $image := resources.GetRemote .Params.media }}
<img src='{{ ( $image.Resize "620x" ).RelPermalink }}' alt="{{ .Params.media_alt}}">

The posts

Within each post I add images using ![alt text](https://example.com/image-url.jpg), in order to apply the powers of Hugo processing to these images, I’m going to have to write a shortcode, and replace those entries (unless someone has something better). I’ve created a very simple shortcode, as seen below, which just takes in a url and alt text, the image is resized to 2000 pixels and has a default quality value of 75.

{{ $img := resources.GetRemote (.Get "img" ) }}
{{ $alt := .Get "alt" }}

<p>
    <img src='{{ ( $img.Resize "2000x" ).RelPermalink }}' alt="{{ $alt }}">
</p>

Now there’s so much more I could be doing like serving multiple image formats or sizes which you can learn about on Mijndert Stuij’s or Bryce Wray’s blog. I will leave that for another day, and possibly update or follow-up to this post in the future.


Related ramblings