Resize images only if larger than target dimensions

I use a script to convert inline markdown images into HTML img tags with srcset alternatives. It produces thumbnails conditinally, otherwise falling back on solely the original. I’ll paste it here, maybe it gives you some ideas:

/layouts/_default/_markup/render-image.html:

{{- $i := .Page.Resources.GetMatch .Destination -}}
{{- if $i -}}
{{- $Wd := $i.Width -}}
<a class="image" href="{{ $i.RelPermalink }}"
{{- with .Title }} data-caption="{{ . }}"{{ end -}}{{- /* Added to <a> tag for lightbox captions */ -}}
><img class="inline" src="{{ $i.RelPermalink }}"
{{- $sizes := slice 300 600 900 1200 -}}{{- /* thumb resolutions to generate for highDPI */ -}}
{{- $srcset := slice -}}
{{- range $sizes -}}
  {{- if lt (mul . 1.2) $Wd -}}{{- /* Only generate this thumb if original is noticeably bigger */ -}}
    {{- $thumb := $i.Resize (printf "%dx" .) -}}
    {{- $srcset = $srcset | append (printf ("%s %dw") $thumb.RelPermalink . ) -}}
  {{- end -}}
{{- end -}}
{{- if gt (len $srcset) 0 -}}{{- /* No srcset if original too small to have any thumbs */ -}}
  {{- (printf " srcset=\"%s\"" (delimit $srcset ", ")) | safeHTMLAttr -}}
  {{- " sizes=\"(min-aspect-ratio: 10/16) 300px, 100vw\"" | safeHTMLAttr -}}
{{- end -}}
{{- with .PlainText }} alt="{{ . }}"{{ end }}
{{- with .Title }} title="{{ . }}"{{ end -}}
></a>
{{- else -}}
  {{- warnf "Unable to find '%s' -- ensure image exists alongside document in page bundle" .Destination -}}
{{- end -}}

300 600 900 1200 and (min-aspect-ratio: 10/16) 300px, 100vw are specific to my site, not general.

3 Likes