Fitness and everything else

Shortcode Now Deals With Rotated Images

Some time ago, I came across a figure short code for Hugo that automatically resizes images. I took that as a base and reworked it a bit to fit my needs and make it more understandable. Over time, I made minor tweaks to it.

Another thing that I had to deal with is my phone has the pictures rotated. I originally dealt with that by having a separate figurerotate short code that I called for those pictures. That solution worked well enough, but I had to decide whether the pictures needed to be rotated or not myself. I wanted something more automated.

Looking at Exif data from the pictures it clicked that I cause use Hugo’s ability to read it to decide whether the images are rotated or not. I don’t understand why this happens with pictures from my phone, but it does for some reason. I wanted to come up with a method to deal with it without me having to think about it or double check.

Below are some snippets from my short code of how I got it working.

First we have to read the Exif data and I set the $Rotate variable to the text of the command for rotating that I want to use based on the position of the picture.

$src is the image.

1{{- with $src.Exif -}}
2{{- if eq .tags.Orientation 6 -}}{{- $Rotate = "r270" -}} {{- end -}}
3{{- if eq .tags.Orientation 3 -}}{{- $Rotate = "r180" -}} {{- end -}}
4{{- if eq .tags.Orientation 8 -}}{{- $Rotate = "r90" -}} {{- end -}}
5 {{- if eq .tags.Orientation 0 -}}{{- $Rotate := "" -}}{{- end -}}
6{{ end }}

Next, I use the $Rotate variable when building the image processing command. It’s really great how powerful the templates are now that I am really getting the hang of them.

{{- $Small := ($src.Resize (printf "%s %s" $Rotate "480x")) | resources.Copy $Name -}}

I will publish the entire shortcode someday when I am happy enough with it, but I wanted to put out these snippets from it as a potential help to someone else looking for a solution to this. This will make it a little more convenient to maintain if something changes in the future since I will have one shortcode to deal with rather than two. I have been trying to consolidate and simplify my shortcodes and partials recently to help with that. A good example is when I modified the previous versions of the code to use the new “resources.Copy” feature that was added to a recent Hugo release. I also moved my images to the assets directory at the time for processing rather than the page bundles I had been using. I could have done those one had I not used two hand coded rotation commands. That was just to make things and file names cleaner.

It’s been a fun and at times frustrating experience, but it’s always rewarding in the end to learn something new and solve problems.