1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-27 05:18:28 -04:00
jarv.is/layouts/partials/functions/optimize-image.html

31 lines
1.3 KiB
HTML

{{/* Automatic scaling/optimization of HiDPI/retina images */}}
{{/* start with the original image located in the requesting page's files */}}
{{ $original := .Page.Resources.GetMatch (.Get "src") }}
{{ $image := $original }}
{{/* default to page width */}}
{{ $setWidth := .Site.Params.Theme.maxWidth }}
{{/* check if a specific size was requested via a parameter & use that instead */}}
{{ if .Get "width" }}
{{ $setWidth = (int (.Get "width")) }}
{{ end }}
{{/* we want HiDPI images, so make the real image size 2x the display size */}}
{{ $retinaWidth := (mul $setWidth 2) }}
{{/* only resize image if it's wider than the set width or page width (times 2) */}}
{{ if gt $original.Width $retinaWidth }}
{{/* let .Resize determine the height itself */}}
{{ $image = $original.Resize (printf "%dx" $retinaWidth) }}
{{ end }}
{{/* calculate the final dimensions for <img> to use, keeping original aspect ratio */}}
{{ $aspectRatio := (div (float $image.Height) $image.Width) }}
{{ $displayWidth := $setWidth }}
{{ $displayHeight := (math.Ceil (mul $aspectRatio $setWidth)) }}
{{/* kick back an object that acts mostly like a normal image! */}}
{{ return (dict "Permalink" $image.Permalink "Width" $displayWidth "Height" $displayHeight "MediaType" $image.MediaType "originalPermalink" $original.Permalink) }}