Image Partial for Asset Processing

Not sure if you know this, but to get the actual width and height of the orginal image you could do

$origHeight := $src.Height
$origWidth := $src.Width

instead of having to pass them in. It depends on whether you want to β€˜force’ to fit a passed in size, or if you just want to know what the size is.

(Does not work with SVG though, nor does the resize and so on that operates on an image resource).

1 Like

Ive updated the img.html partial to below and it works great!

{{ $src := resources.Get .url }}

{{/* set image sizes, these are hardcoded for now, x dictates that images are resized to this width */}}

{{ $origHeight := $src.Height }}
{{ $origWidth := $src.Width }}

{{ $tinyw := default β€œ500x webp” }}
{{ $smallw := default β€œ883x webp” }}
{{ $mediumw := default β€œ1200x webp” }}
{{ $largew := default β€œ1500x webp” }}

{{/* resize the src image to the given sizes */}}

{{ $tiny := $src.Resize $tinyw }}
{{ $small := $src.Resize $smallw }}
{{ $medium := $src.Resize $mediumw }}
{{ $large := $src.Resize $largew }}

{{/* add the processed images to the scratch */}}

{{ $tiny = $tiny.RelPermalink }}
{{ $small = $small.RelPermalink }}
{{ $medium = $medium.RelPermalink }}
{{ $large = $large.RelPermalink }}

{{/* only use images smaller than or equal to the src (original) image size, as Hugo will upscale small images /}}
{{/
set the sizes attribute to (min-width: 35em) 1200px, 100vw unless overridden */}}

img
sizes=β€œ(min-width: 35em) 845px, 100vw”
srcset=’
{{ if ge $src.Width β€œ500” }}
{{ with $tiny }}{{.}} 500w{{ end }}
{{ end }}
{{ if ge $src.Width β€œ845” }}
{{ with $small }}, {{.}} 845w{{ end }}
{{ end }}
{{ if ge $src.Width β€œ1200” }}
{{ with $medium }}, {{.}} 1200w{{ end }}
{{ end }}
{{ if ge $src.Width β€œ1500” }}
{{ with $large }}, {{.}} 1500w {{ end }}
{{ end }}’
src=β€œ{{ $src.RelPermalink }}” alt=β€œ{{ .alt }}” loading=β€œ{{.loading}}” width=β€œ{{ $origWidth }}” height=β€œ{{ $origHeight }}”

Thank you everyone who helped especially Daniel F. Dickinson

1 Like

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