Hello, friends!
I have a simple image shortcode called webp.html, shown below:
{{- $src := .Get "src" -}}
{{- $alt := .Get "alt" -}}
{{- $img := resources.Get (printf "images/%s" $src) -}}
{{- if $img -}}
{{- $resized := $img.Resize "640x webp q80" -}}
<img
class="w-full max-w-[640px] mx-auto rounded-lg mb-8"
src="{{ $resized.RelPermalink }}"
alt="{{ $alt }}"
width="{{ $resized.Width }}"
height="{{ $resized.Height }}"
loading="lazy"
decoding="async"
/>
{{- else -}}
<p class="text-red-600">Image "{{ $src }}" doesn't exist in assets/images/</p>
{{- end -}}
This shortcode is supposed to resize images to 640px width and convert them to webp format.
In my content files, I use it like this:
{{< webp src="imageName.png" alt="Alt text" >}}
Everything works fine, except when the original image is smaller than 640 px wide.
I thought Hugo wouldn’t upscale images when using .Resize "640x", but in my case, smaller images still increased, which decreases the quality of the image.
How can I modify the shortcode so that:
-
if the original image is larger than 640 px (width), it resizes it down to 640 px;
-
but if it’s smaller, it just converts it to webp (with q80) without resizing?
Thanks in advance for your help!