How I Converted My Hugo Blog Images to WebP (Without Changing Size or Aspect Ratio)

ashley chow Ru2mQwrfc2g unsplash scaled
Genx Avatar
Share This:

Converting your images to WebP can make your Hugo website load faster without sacrificing quality. Here’s how I achieved it, while ensuring that the images in my assets/images folder kept their original dimensions and aspect ratios.

1. Modifying the Template to Use Hugo’s Image Processing

Initially, my post_preview template looked like this:

{{ if .Params.image }}
    <img src="{{ .Params.image }}" alt="{{ .Title }}" class="img-title" />
{{ end }}

This made Hugo directly use the file specified in the front matter, with no processing.

To automatically convert images to WebP (without resizing), I updated the template to let Hugo’s asset pipeline process and transform the images in the assets/images directory:

{{ with resources.Get (printf "images/%s" .Params.image) }}
  {{ with .Resize (printf "%dx%d webp" .Width .Height) }}
    <img src="{{ .RelPermalink }}" alt="{{ $.Title }}" class="img-title u-photo" style="max-width: 100%; height: auto;">
  {{ end }}
{{ end }}

What this does:

  • resources.Get loads the image from assets/images/.
  • .Resize (printf "%dx%d webp" .Width .Height) generates a WebP version in the original width and height (no resizing or cropping).
  • The resulting <img> tag will reference the converted WebP image.

2. Updating Markdown Front Matter

Previously, many of my Markdown files pointed to images with a path, e.g.,

image = "assets/images/nameoftheimage.jpg"

Because my image processing code expects only the filename (not the full path), I updated the front matter in each .md file to just use the image name:

image = "nameoftheimage.jpg"

This matches the template logic, which looks for the image inside assets/images using resources.Get.

3. Result

  • All images referenced in posts are now automatically converted to WebP before being served, reducing file size and loading time.
  • No resizing or dimension/aspect ratio changes occur, because .Width and .Height are taken from the original image.
  • The change is fully automated – you only need to specify the base filename in your posts’ front matter.

4. Tips and Notes

  • You’ll need to ensure all the images referenced are actually in the assets/images folder.
  • If you ever want to process images differently (e.g., add resizing or cropping), Hugo’s asset pipeline can easily be adjusted for that.
  • This approach keeps your blog fast and your images well-optimized, with no extra manual work after setup.

By making these two simple changes, modifying the template to process images and standardizing image filenames in front matter—my blog now uses modern, efficient WebP images everywhere, painlessly.

Related Posts

Genx

in

Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

17 − seven =

Webmention: Have you posted a response to this article? Let me know the URL: