Hugo has various image processing operations builtin such as resizing, downsizing, cropping, accessing Exif data, rotating, filters and encoding images in different formats (bmp, gif, jpeg, jpg, png, tif, tiff, or webp).
File: <theme_dir>/layouts/partial/ImageConverter.html
{{/* Step 1: A default image as fallback */}}
{{ $image := "/images/placeholder.png" }}
{{/* Step 2: now check if passed image exists with same as title */}}
{{ $image_url := resources.Get .ImageSrc }}
{{ $img_param := .ImgParam }}
{{ if $image_url }}
{{/* Resize and convert the image */}}
{{ $image_url = $image_url.Resize $img_param }}
{{ $image = $image_url.RelPermalink }}
{{end}}
{{return $image}}
Above partial take 2 parameter ImageSrc and ImgParam. If a image matching resources.Get exists, the code resizes and converts it to webp format using the Resize method, and reassigns the resulting image URL to the $image variable. If no matching resource was found a fallback placeholder.png image is used. Finally, the partial returns the $image variable to the calling template
ImageConverter.html partial is fully reusable. It can convert different formats (bmp, gif, jpeg, jpg, png, tif, tiff, or webp)
Example to convert to png format you need to change ImgParam parameter to png
{{- $image_png := partial "ImageConverter.html" (dict "ImageSrc" .Destination "ImgParam" (printf "%dx%d png q100" $image.Width $image.Height)) -}}
Usage of the partial explained on this article Hugo: How to generate Webp images for your websites & blog