How do I turn a genericResource into an image?

I want to image process a certain page resource:

{{- $img := .Page.Resources.GetMatch .Destination -}}
{{- with $img -}}
{{ $img.Fit "600x600"}}

fails with “at <$img.Fit>: error calling Fit: *resources.genericResource is not an image”

In reality this is an image, of course, I just assume that GetMatch does not return it as such, as ByType would.

What do I need to change?


The following construct is battle tested:

{{- $img := .Page.Resources.GetMatch (printf "%s" (.Destination | safeURL)) -}}

.Destination is converted into a string with the printf function and then piped with safeURL.

Ok, this is a bit safer, it seems, but still seems not to return an image that can be processed (and by looking at the code, why should it).

{{- $img := .Page.Resources.GetMatch (printf "%s" (.Destination | safeURL)) -}}
{{- with $img -}}
{{ .Fit "600x600" }}
<img src="{{ .RelPermalink }}" alt="{{ $.Text }}" title="{{ with $.Title }}{{ . }}{{ end }}" />

still throws

at <.Fit>: error calling Fit: *resources.genericResource is not an image

Or am I getting something wrong?

Instead of the above try something like {{ $thumb := $img.Fit "600x600" }}

The Image Processing Methods need to be used along with the image resource.

Instead of the above try something like {{ $thumb := $img.Fit "600x600" }}

I tried that of course, same outcome.
“with” seems to set the context to its parameter within its scope. So in that
place “.” and “$img” should reference the very same object.

I wonder if this could happen, if somewhere in some content, there is a webp image referenced …

@alexandros, yeah, that was it. Sadly Hugo cannot handle webp yet, so if you reference one somewhere, as soon as you try any manipulation on it, the whole site crashes.
I issued

find . -name *.webp -exec mogrify -format jpg {} \;
find . -name *.webp -exec rm {} \;

in my content folder and used my text editor to search and replace for “webp” to “jpg”.
Now it works.

Since Hugo’s image processing is mostly useful for JPEGs anyway, I’d go somewhat like

{{ if and (eq $img.ResourceType "image") (eq $img.MediaType.SubType "jpeg") }}
{{ $img.Fit "600x600" }}
{{ end }}

Why shouldn’t this apply to pngs and webp just as well? I have got lots of pngs here.

In my eyes lacking support for webp is just an oversight on hugo’s part, but I am certain this will be rectified at a certain point in the future. For what I could gather there is no real support for webp on golang, which is kind of ironic.

It’s not that you shoudn’t apply this to PNGs, it’s just that in my experience PNGs, when used appropriately, are small enough anyway to not be worth the hassle of the image processing. Your mileage, usecase and template code may wary. :slight_smile:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.