Last active
March 30, 2020 23:25
-
-
Save johnsvenn/4792589a946f76d58d968b9f88cf5896 to your computer and use it in GitHub Desktop.
Hugo shortcode to resize an image and rotate using Exif data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ $src := .Page.Resources.GetMatch (printf "*%s*" (.Get "src")) }} | |
{{ if eq $src nil }} | |
{{ $src = .Page.Parent.Resources.GetMatch (printf "*%s*" (.Get "src")) }} | |
{{ end }} | |
{{ if not (eq $src nil) }} | |
{{ $rotateBy := default "" }} | |
{{ $thumb := "150x150" }} | |
{{ $default := "400x" }} | |
{{ with $src }} | |
{{/* If the exif data is missing */}} | |
{{ $orientation := 1 }} | |
{{ if in "jpg tiff" .MediaType.SubType }} | |
{{ with .Exif }} | |
{{ $orientation = .Tags.Orientation }} | |
{{ end }} | |
{{ end }} | |
{{/* https://sirv.com/help/articles/rotate-photos-to-be-upright/#EXIF_orientation_values*/}} | |
{{ if eq $orientation 1 }} | |
{{/* Do nothing, image is right-side up */}} | |
{{ else if (eq $orientation 2) }} | |
{{/* Do nothing back to front */}} | |
{{ else if (eq $orientation 3) }} | |
{{/* Upside down */}} | |
{{ $rotateBy = "r180" }} | |
{{ else if (eq $orientation 4) }} | |
{{/* Upside down and back to front */}} | |
{{ $rotateBy = "r180" }} | |
{{ else if (eq $orientation 5) }} | |
{{/* On its side */}} | |
{{ $rotateBy = "r270" }} | |
{{ else if (eq $orientation 6) }} | |
{{/* On its side and back to front */}} | |
{{ $rotateBy = "r270" }} | |
{{ else if (eq $orientation 7) }} | |
{{ $rotateBy = "r90" }} | |
{{ else if (eq $orientation 8) }} | |
{{ $rotateBy = "r90" }} | |
{{ end }} | |
{{ end }} | |
{{ .Scratch.Set "thumb" ($src.Resize (printf "%s %s" $thumb $rotateBy)) }} | |
{{ .Scratch.Set "default" ($src.Resize (printf "%s %s" $default $rotateBy)) }} | |
{{ $thumb := .Scratch.Get "thumb" }} | |
{{ $default := .Scratch.Get "default" }} | |
{{ $type := "default" }} | |
{{ with .Get "type" }} | |
{{ $type = . }} | |
{{ end }} | |
<img | |
{{ if eq $type "thumb" }} | |
src="{{ $thumb.RelPermalink }}" | |
{{ else }} | |
src="{{ $default.RelPermalink }}" | |
{{ end }} | |
{{ with .Get "alt" }}alt="{{.}}"{{ else }}alt=""{{ end }} | |
{{ with .Get "class" }}class="{{.}}"{{ end }} | |
> | |
{{ end }} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment