s

Resizing images using shortcodes

By Angela C

April 20, 2021 in shortcodes images

Reading time: 2 minutes.

Resizing images in Hugo using shortcodes.

When creating plots with Python in matplotlib or Seaborn, a figure size can be set instead of using the default size. These images can be saved or exported and then used in a post such as this. If the saved image is too big or small it can be resized.

Hugo has a section under content management for image processing.

Hugo has built-in methods for altering images that are provides as page resources. Anything in a page bundle is a page resource.

{{ $image := $.Page.Resources.Get("path to image file.png)}}
{{ $smallImage := $image.Resize "524x" }}

The image resource implements the Resize, Fit, Fill, and Filter methods, where each returns a transformed image using the specified dimensions and processing options.

Some options shown on the Hugo documentation:

Resize

// Resize to a width of 600px and preserve ratio
{{ $image := $resource.Resize "600x" }}
// Resize to a height of 400px and preserve ratio
{{ $image := $resource.Resize "x400" }}

// Resize to a width 600px and a height of 400px
{{ $image := $resource.Resize "600x400" }}

Fit

Fit will scale down the image to fit the given dimensions while maintaining aspect ratio. Both height and width are required.

{{ $image := $resource.Fit "600x400" }}

I do not see any options to center the images in the documentation. The Anchor option only works with the Fill method which is mainly used for thumbnail generation. It doesn’t work with the Resize method. For now, as I am using Bootstrap4, I have added a bootstrap class to center the image to the image src tag. This is working so I will leave it for now. I’m not sure if it would be the recommended way.

The bootstrap class class="mx-auto d-block" can be used to set the margins to auto and the display block to the image.

Instead of editing the shortcode for project images I have created a new shortcode to use with images that were generated from Jupyter notebooks.


Changing images setting or removing and renaming images will result in unused images taking up space and cluttering the project.

To clean up unused images run hugo --gc.