Lesson Overview

Images

Learn how to compress and optimize your images for the web using Hugo.
3 minutes 508 words

Now that we have our site setup, we may want to add images to our posts or our layouts.

The easiest way to do this is to use the static folder.

Static

The static folder in our project is another special Hugo feature. Hugo will allow anything in the static folder to be accessed easily inside markdown posts or in layouts, just by using a slash /.

For example: place an image inside the static folder. Then go to your Markdown blog post and use the image syntax to reference the new image.

If I saved an image of a duck called duck.png inside my static folder, then in my blog post I would write ![Yellow Duck](/duck.png 'Yellow Duck') to display it.

It’s as simple as that! BUT there is one important thing to know about images and the internet - larger images take longer to load.

Every time a user visits our site, they must download all the HTML files, CSS files and images that are needed for the browser to display the page correctly, so the bigger the files, the longer it takes for the page to load - and slow load times = a bad time.

To easily address this issue, we can use assets.

Assets

Assets are another special feature in Hugo because they provides us some functions in our templates to shrink or compress images so the final size is smaller and load faster.

Keep in mind that when images are compressed, some quality can degrade, but most of the time it is not noticeable.

To test out this compression, create a folder called assets at the root of your project, then move your image out of the static folder and into this new assets folder.

Then to compress the image, go to a template HTML file and write the following:

{{ $asset := resources.Get "/duck.png" }}
{{ $img := $asset.Fit "600x400" }}
<figure class="image is-3by2">
  <img alt="Yellow Duck" src="{{ $img.RelPermalink }}" />
</figure>

First we get the asset by it’s name and save it to the $asset variable. Then we resize the image to 600 pixels by 400 pixels and save that to the variable $img. Then we use the $img.RelPermalink inside the HTML <img> tag to display our new compressed image! We also use Bulma’s CSS classes to make sure the image scales nicely on larger and smaller screens.

Shortcodes

You may be wondering why we used Markdown for images in the static folder, but HTML Templates for images in the assets folder, and this is because we only have access to the compressing functions inside Templates and not inside Markdown.

But there is a way to give access to content authors to compress images easily inside Markdown by using custom shortcodes, which is a Hugo feature that allows us to create our own syntax and logic for use inside Markdown.

Custom Shortcodes are beyond the scope of this mini course, but if you are interested in learning more about their use cases, take a look at Hugo’s docs about them.

Share this page