feat: add file types whitelist for image processing (#885)

Add `allowedTypes` and `resizableTypes` to `imageProcessing` configuration

Prior to this commit, SVG images were not processed by `render-image.html` because SVG does not have a physical dimension like JPEG. This logic was done using a conditional.

I have now realised that Hugo can be very slow when resizing `gif` images. So I created this whitelist mechanism:

- `allowedTypes`: image types with width and height attributes
- `resizableTypes`: image types that can be resized

Here's a list of media types: bmp, gif, jpeg, png, svg+xml, tiff, webp

https://gohugo.io/templates/output-formats/#media-types
This commit is contained in:
Jimmy Cai 2023-10-11 22:51:42 +02:00 committed by GitHub
parent d941e22120
commit 8dc2880a9c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 7 deletions

View File

@ -146,6 +146,15 @@ colorScheme:
default: auto default: auto
imageProcessing: imageProcessing:
allowedTypes:
- jpeg
- png
- gif
- webp
resizableTypes:
- jpeg
- png
- webp
cover: cover:
enabled: true enabled: true
content: content:

View File

@ -4,20 +4,24 @@
{{- $Width := 0 -}} {{- $Width := 0 -}}
{{- $Height := 0 -}} {{- $Height := 0 -}}
{{- $Srcset := "" -}} {{- $Srcset := "" -}}
{{- $imageProcessing := .Page.Site.Params.imageProcessing.content.enabled -}}
{{/* SVG and external images won't work with gallery layout, because their width and height attributes are unknown */}} {{- $allowedTypes := .Page.Site.Params.ImageProcessing.AllowedTypes -}}
{{- $resizableTypes := .Page.Site.Params.ImageProcessing.ResizableTypes -}}
{{- $galleryImage := false -}} {{- $galleryImage := false -}}
{{- if $image -}} {{- if $image -}}
{{- $notSVG := ne (path.Ext .Destination) ".svg" -}} {{- $type := $image.MediaType.SubType -}}
{{- $allowed := in $allowedTypes $type -}}
{{- $resizable := in $resizableTypes $type -}}
{{- $imageProcessing := and $imageProcessing $resizable -}}
{{- $Permalink = $image.RelPermalink -}} {{- $Permalink = $image.RelPermalink -}}
{{- if $notSVG -}} {{- if $allowed -}}
{{- $Width = $image.Width -}} {{- $Width = $image.Width -}}
{{- $Height = $image.Height -}} {{- $Height = $image.Height -}}
{{- $galleryImage = true -}} {{- $galleryImage = true -}}
{{- if .Page.Site.Params.imageProcessing.content.enabled -}} {{- if $imageProcessing -}}
{{- $small := $image.Resize `480x` -}} {{- $small := $image.Resize `480x` -}}
{{- $big := $image.Resize `1024x` -}} {{- $big := $image.Resize `1024x` -}}
{{- $Srcset = printf `%s 480w, %s 1024w` $small.RelPermalink $big.RelPermalink -}} {{- $Srcset = printf `%s 480w, %s 1024w` $small.RelPermalink $big.RelPermalink -}}