I have some portrait images I’d like to show in full in previews in Whatsapp, Linkedin,etc through the Hugo opengraph template. So I’m wondering if 1) Does Hugo Image Processing support making landscape images out of portrait images with e.g. a white background on both sides of the image? 2) Presumably I would have to edit the opengraph template to do the image processesing on build. Thanks for thoughts on this!
The best I can come up with is creating a white canvas image, then overlaying the portrait image. Hugo can’t create an empty image, so create a single pixel white image that we’ll resize to create the canvas. Using ImageMagick:
convert -size 1x1 xc:white white-pixel.png
Here’s the site structure:
assets/
└── images/
└── white-pixel.png
content/
├── posts/
│ ├── post-1/
│ │ ├── index.md
│ │ └── og.jpg
│ └── post-2/
│ ├── index.md
│ └── og.jpg
└── _index.md
This handles both portrait and landscape images, producing a WebP image that is 1200x629. Change the $t
options as needed.
{{/* Image processing options for target image. */}}
{{ $t := dict "width" 1200 "height" 629 "anchor" "smart" "format" "webp" }}
{{/* Render. */}}
{{ with .Resources.Get "og.jpg" }}
{{ if lt (div .Width .Height) 1 }}
{{/* Portrait image. */}}
{{ $rCanvas := (resources.Get "images/white-pixel.png").Fill (printf "%dx%d %s" $t.width $t.height $t.format) }}
{{ $rOverlay := .Resize (printf "x%d" $t.height) }}
{{ $xOffset := div (sub $rCanvas.Width $rOverlay.Width) 2 }}
{{ with $rCanvas | images.Filter (images.Overlay $rOverlay $xOffset 0) }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ else }}
{{/* Landscape image. */}}
{{ with .Fill (printf "%dx%d %s %s" $t.width $t.height $t.anchor $t.format) }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
{{ end }}
Example
git clone --single-branch -b hugo-forum-topic-42000 https://github.com/jmooring/hugo-testing hugo-forum-topic-42000
cd hugo-forum-topic-42000
hugo server
1 Like
Thank you! That looks impressive. Thank you!
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.