HUGO

Render hook for image compression

I keep a blog where I post photos. Some posts have hi-res photography which I want to be compressed automatically, but I don’t want all images to be compressed, just *.jpgs which are more than 1280px wide.

I wrote this render hook:

layouts/_default/_markup/render-image.html

{{- $source := .Destination -}}
{{- $original := .Page.Resources.GetMatch .Destination -}}
{{- if not (eq $original nil) -}}
  {{- $source = $original.RelPermalink -}}
  {{- $islarge := gt $original.Width 1280 -}}
  {{- $isjpg := in ".jpg .jpeg" (path.Ext $source) -}}
  {{- if and ($isjpg) ($islarge) -}}
    {{- $source = ($original.Resize "1280x q80").RelPermalink -}}
  {{- end -}}
{{- end -}}
<img src="{{ $source }}" alt="{{ .Text }}" {{ with .Title}} title="{{ . }}"{{ end }} />

Because this uses the .Page.Resources feature, it works as long as your markdown is written using page-bundle-relative image links, e.g.

![alt text](image.jpg)

If you have any suggestions for improvements, let me know! Enjoy.

1 Like

Here’s an updated version which will check the file size in bytes to determine if the resize should occur:

<!-- this render hook compresses jpg/jpeg files that are > 2mb -->
{{- $twoMb := 2000000 -}}
{{- $source := .Destination -}}
{{- $original := .Page.Resources.GetMatch .Destination -}}
{{- if not (eq $original nil) -}}
  {{- $source = $original.RelPermalink -}}
  {{- $islarge := gt (len $original.Content) $twoMb -}}
  {{- $isjpg := in ".jpg .jpeg" (path.Ext $source) -}}
  {{- if and ($isjpg) ($islarge) -}}
    {{- $source = ($original.Resize "1280x q80").RelPermalink -}}
  {{- end -}}
{{- end -}}
<img src="{{ $source }}" alt="{{ .Text }}" {{ with .Title}} title="{{ . }}"{{ end }} />

Solid work!