Decrease image size and quality

Hello. I need to reduce the image size and quality of the images in this code that displays the last 10 posts.

		{{ range ( where .Site.RegularPages "Type" "post" | first 20 ) }}
		<a href="{{ .Permalink }}"><img class="posts__img" title="{{ .Title }}" alt="{{ .Params.pretitle }}"
				src="{{ .Site.BaseURL }}{{ .Params.imagepost }}" alt=""></a>
		{{end}}

Help me, please!

Place the image(s) in the assets folder (e.g. assets/images/image-name.jpg). Then reference the same path in your page front matter, e.g for YAML imagepost: "/images/image-name.jpg" and then use the code below

{{- range ( where .Site.RegularPages "Type" "post" | first 20 ) }}
<a href="{{ .Permalink }}">
  {{- with resources.Get .Params.imagepost }}
  {{- with .Fill "510x369 q70"}}
  <img class="posts__img" title="{{ .Title }}" alt="{{ .Params.pretitle }}"
    src="{{ .Permalink }}" alt=""></a>
  {{ end }}
  {{- end }}

Alternatively, If you are using leaf bundles, which I recommend, you can do it like the code below

{{- range ( where .Site.RegularPages "Type" "post" | first 20 ) }}
<a href="{{ .Permalink }}">
  {{- with .Resources.GetMatch "cover.*" }}
  {{- with .Fill "510x369 q70"}}
  <img class="posts__img" title="{{ .Title }}" alt="{{ .Params.pretitle }}"
    src="{{ .Permalink }}" alt=""></a>
  {{ end }}
  {{- end }}

You don’t need to specify imagepost in frontmatter with this method. Just make sure all the featured images in your leaf bundles have the same title (e.g cover.jpg).

For either method, change the .Fill dimensions to the size you want and the q50 to the quality you want. By default, Hugo’s image quality is set at q70.

If you need to convert your images to webP, add webp just after the image dimensions, e.g. 510x369 webp q70.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.