Detecting image size inside of a Shortcode

I’m wanting to create a short code that stubs out the html that I want when rendering images. As part of this I need to know the dimensions of the source image so that I can lay things out correctly so that I don’t get content jumping down the page as images load in.

Currently I’m thinking of creating a gulp task that looks for images in the generated hugo output and then replaces it with the stub I need, but that won’t really work all that well with hugo server. Hence why I’m thinking there must be a way of reading the image dimensioned from within the Shortcode but don’t quite know enough Go to pull this off.

Any pointers?

Note, I know there are other topics talking about generating different sizes of an images, etc… here I am just trying to keep it simple and read the image size.

1 Like

You can use the imageConfig function for that in Hugo. See here for more.

1 Like

Here’s the shortcode (that works for me) to detect image size inside Hugo.

`
{{ $src := .Get “src” }}
{{ $config := imageConfig (printf “/static/%s” $src) }}
<img src="{{ $.Page.Site.BaseURL }}{{ .Get “src” }}" alt="{{ .Get “title” }}" {{ if or (.Get “alt”) (.Get “caption”) }}alt="{{ with .Get “alt”}}{{.}}{{else}}{{ .Get “caption” }}{{ end }}"{{ end }} height="{{$config.Height}}" width="{{$config.Width}}" />

`

And on each markdown I use it like so:

{{< img src="PATH TO IMAGE" title="Lorem Ipsum">}}

3 Likes