Stop creating resized images larger than the original

I have a list of image sizes I want to resize an image to, and I don’t want to produce resized images larger than the original image.

Here’s the list of image sizes in my config.toml:

[params]
  bodyPhotoWidths = [540, 720, 1080, 1440, 2160, 2880, 3600]
  bodyWidthPX = "720"

And here’s the shortcode that resizes the images:

{{/* get file that matches the filename as specified as src="" in shortcode */ -}}
{{ $src := .Page.Resources.GetMatch (printf "*%s*" (.Get "src")) -}}

{{ $imgSrc := "" -}}
{{ $imgSrcSet := slice -}}

{{ $widths := $.Site.Params.bodyPhotoWidths -}}
{{ $body := $.Site.Params.bodyWidthPX | default 720 -}}

{{ range $widths -}}
  {{ $srcUrl := (printf "%dx" . | $src.Resize).RelPermalink -}}
  {{ if eq $imgSrc "" }}{{ $imgSrc = $srcUrl }}{{ end -}}
  {{ if ge $src.Width . -}}
	{{ $imgSrcSet = $imgSrcSet | append (printf "%s %dw" $srcUrl .) -}}
  {{ end -}}
{{ end -}}
{{ $imgSrcSet = (delimit $imgSrcSet ",\n\t") -}}

<img
	src="{{ $imgSrc }}"
	{{ with .Get "sizes" }}sizes='{{.}}'{{ else -}}
	sizes="(min-width: {{ $body }}px) {{ $body }}px, (max-width: {{ $body }}px) 100vw"
	{{ end -}}
	srcset="{{ $imgSrcSet }}"
	{{ with .Get "alt" }}alt="{{.}}"{{ else }}alt=""{{ end }}
	class=imgbody>

This technically works, it only lists images that are smaller than the original image, but it is still creating resized images that are larger than the original image (and simply not printing the urls in HTML). It would be better if we could eliminate the listed image sizes that are larger than the original image and not produce them at all. How would you rewrite this? With range where? I can’t get the syntax right or something, everything I’ve tried has either resulted in errors or no image sizes being used at all. I imagine something like:
{{ range where $widths "le" $src.Width -}}

The resized images get created once you call the .RelPermalink. You can move that line to inside the if block that tests the width (untested, but you get the idea):

  {{ if ge $src.Width . -}}
  {{ $srcUrl := (printf "%dx" . | $src.Resize).RelPermalink -}}
  {{ if eq $imgSrc "" }}{{ $imgSrc = $srcUrl }}{{ end -}}
	{{ $imgSrcSet = $imgSrcSet | append (printf "%s %dw" $srcUrl .) -}}
  {{ end -}}
1 Like

Now that you point it out, it’s obvious! :smiley: Thank you so much.

I guess I still have no idea how to use the “range where” syntax, but I no longer care.

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