Why does .Resize increase the image size even when the original asset size is smaller?

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!

what about checking the size first and dont resize in case

width

1 Like

You require a certain size and Hugo obeys. How would it deduce that you don’t want images to be upscaled?
Follow the advice of @irkode and check image dimensions first. Though your class might then not match the image’s size…

1 Like

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