Thumbnail Images on your Hugo Blog Posts

Hugo now has the ability to do image resizing, cropping, quality-changing, etc (hooray!) - so how do we use it? In this post we take a look at how to resize images automatically using Hugo. There’s a few different ways to achieve this, depending on what you’re trying to do.

In a Theme - “I want to make thumbnails!”

You might run a blog, which on the home page has a list of your blog posts. And lets say you want to show a thumbnail image for each of your posts. This is the scenario we’ll be looking into here.

Important! Make sure your images are not stored in the /static/ folder

In our example, our theme displays the lists of posts in layouts/_default/summary.html

It looks a little like this (I’ve simplified it a bit):

1
2
3
4
5
6
<div class="item">
    <a href="{{ .Permalink }}">
        <h1>{{ .Title }}</h1>
        {{ .Summary }}
    </a>
</div>

In our example, each of our posts have featured_image in the properties of the markdown file which was can use to know which is the “primary” image of the page. We can then add our images to this summary file by using resources.Get to get the photos.

In Markdown:

1
featured_image: /img/2020/hugos-parachute.jpg

In Theme:

1
2
{{- $image := resources.Get .Params.featured_image -}}
<img src="{{ ($image.Fill "200x200 q100 Center").RelPermalink }}">

So, all together it becomes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<div class="item">
    <a href="{{ .Permalink }}">
        {{- $image := resources.Get .Params.featured_image -}}
        <img src="{{ ($image.Fill "200x200 q100 Center").RelPermalink }}">
        <div>
            <h1>{{ .Title }}</h1>
            {{ .Summary }}
        </div>
    </a>
</div>

The line $image.Fill "200x200 q100 Center" can be changed, as we’re making an image with 200px width and 200px height, at 100 quality (crop to the center).

If we sprinkle on some final css style to tidy things up:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
.item { 
    clear: both; 
}
.item img { 
    float:left; 
    width: 20%; 
    box-shadow: 0 0 14px rgba(0,0,0,.2);
}
.item div { 
    float:left; 
    width: 80%; 
    padding-left: 20px 
}
.item h1 {
    margin: 0;
}

End Result:

automatic thumbnails in hugo