Resize images only if larger than target dimensions

Is there a way to tell the .Resize method to only resize if the source image is
smaller than the requested dimensions?

Context: I use the resize method to resize my blog’s images to a max width of 800px, but some posts have images that are smaller than 800px and resizing them makes them blurry.

I’ve looked at https://gohugo.io/content-management/image-processing/#resize but there doesn’t seem to be any options for that.

Thanks

I think you should use the imageConfig function to return the width and height, with the conditional statement. (if width < 800 then …)

Images have a Width and Height, so you can do:

{{ $img := resources.Get "myimage.jpg" }}
{{ if gt $img.Width 800 }}
{{ img = $img.Resize "800x" }}
{{ end }}
1 Like

Thanks Bjorn, Cheng! I will give that a try.

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.

1 Like