-
Notifications
You must be signed in to change notification settings - Fork 19
/
optimize-image.html
30 lines (23 loc) 路 1.29 KB
/
optimize-image.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{{/* 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) }}