Debian Codegraph @

resources/images/filters.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package images provides template functions for manipulating images.
15 package images
16
17 import (
18 "fmt"
19 "image/color"
20 "strings"
21
22 "github.com/gohugoio/hugo/common/hmaps"
23 "github.com/gohugoio/hugo/common/hugio"
24 "github.com/gohugoio/hugo/resources/resource"
25 "github.com/makeworld-the-better-one/dither/v2"
26 "github.com/mitchellh/mapstructure"
27
28 "github.com/gohugoio/gift"
29 "github.com/spf13/cast"
30 )
31
32 // Increment for re-generation of images using these filters.
33 const filterAPIVersion = 0
34
35 type Filters struct{}
36
37 // Process creates a filter that processes an image using the given specification.
38 func (*Filters) Process(spec any) gift.Filter {
39 specs := strings.ToLower(cast.ToString(spec))
40 return filter{
41 Options: newFilterOpts(specs),
42 Filter: processFilter{
43 spec: specs,
44 },
45 }
46 }
47
48 // Overlay creates a filter that overlays src at position x y.
49 func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter {
50 return filter{
51 Options: newFilterOpts(src.Key(), x, y),
52 Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)},
53 }
54 }
55
56 // Mask creates a filter that applies a mask image to the source image.
57 func (*Filters) Mask(mask ImageSource) gift.Filter {
58 return filter{
59 Options: newFilterOpts(mask.Key()),
60 Filter: maskFilter{mask: mask},
61 }
62 }
63
64 // Opacity creates a filter that changes the opacity of an image.
65 // The opacity parameter must be in range (0, 1).
66 func (*Filters) Opacity(opacity any) gift.Filter {
67 return filter{
68 Options: newFilterOpts(opacity),
69 Filter: opacityFilter{opacity: cast.ToFloat32(opacity)},
70 }
71 }
72
73 // Text creates a filter that draws text with the given options.
74 func (*Filters) Text(text string, options ...any) gift.Filter {
75 tf := textFilter{
76 text: text,
77 color: color.White,
78 size: 20,
79 x: 10,
80 y: 10,
81 alignx: "left",
82 aligny: "top",
83 linespacing: 2,
84 }
85
86 var opt hmaps.Params
87 if len(options) > 0 {
88 opt = hmaps.MustToParamsAndPrepare(options[0])
89 for option, v := range opt {
90 switch option {
91 case "color":
92 if color, ok, _ := toColorGo(v); ok {
93 tf.color = color
94 }
95 case "size":
96 tf.size = cast.ToFloat64(v)
97 case "x":
98 tf.x = cast.ToInt(v)
99 case "y":
100 tf.y = cast.ToInt(v)
101 case "alignx":
102 tf.alignx = cast.ToString(v)
103 if tf.alignx != "left" && tf.alignx != "center" && tf.alignx != "right" {
104 panic("alignx must be one of left, center, right")
105 }
106 case "aligny":
107 tf.aligny = cast.ToString(v)
108 if tf.aligny != "top" && tf.aligny != "center" && tf.aligny != "bottom" {
109 panic("aligny must be one of top, center, bottom")
110 }
111
112 case "linespacing":
113 tf.linespacing = cast.ToInt(v)
114 case "font":
115 if err, ok := v.(error); ok {
116 panic(fmt.Sprintf("invalid font source: %s", err))
117 }
118 fontSource, ok1 := v.(hugio.ReadSeekCloserProvider)
119 identifier, ok2 := v.(resource.Identifier)
120
121 if !(ok1 && ok2) {
122 panic(fmt.Sprintf("invalid text font source: %T", v))
123 }
124
125 tf.fontSource = fontSource
126
127 // The input value isn't hashable and will not make a stable key.
128 // Replace it with a string in the map used as basis for the
129 // hash string.
130 opt["font"] = identifier.Key()
131
132 }
133 }
134 }
135
136 return filter{
137 Options: newFilterOpts(text, opt),
138 Filter: tf,
139 }
140 }
141
142 // Padding creates a filter that resizes the image canvas without resizing the
143 // image. The last argument is the canvas color, expressed as an RGB or RGBA
144 // hexadecimal color. The default value is `ffffffff` (opaque white). The
145 // preceding arguments are the padding values, in pixels, using the CSS
146 // shorthand property syntax. Negative padding values will crop the image. The
147 // signature is images.Padding V1 [V2] [V3] [V4] [COLOR].
148 func (*Filters) Padding(args ...any) gift.Filter {
149 if len(args) < 1 || len(args) > 5 {
150 panic("the padding filter requires between 1 and 5 arguments")
151 }
152
153 var top, right, bottom, left int
154 var ccolor color.Color = color.White // canvas color
155
156 _args := args // preserve original args for most stable hash
157
158 if vcs, ok, err := toColorGo(args[len(args)-1]); ok || err != nil {
159 if err != nil {
160 panic("invalid canvas color: specify RGB or RGBA using hex notation")
161 }
162 ccolor = vcs
163 args = args[:len(args)-1]
164 if len(args) == 0 {
165 panic("not enough arguments: provide one or more padding values using the CSS shorthand property syntax")
166 }
167 }
168
169 var vals []int
170 for _, v := range args {
171 vi := cast.ToInt(v)
172 if vi > 5000 {
173 panic("padding values must not exceed 5000 pixels")
174 }
175 vals = append(vals, vi)
176 }
177
178 switch len(args) {
179 case 1:
180 top, right, bottom, left = vals[0], vals[0], vals[0], vals[0]
181 case 2:
182 top, right, bottom, left = vals[0], vals[1], vals[0], vals[1]
183 case 3:
184 top, right, bottom, left = vals[0], vals[1], vals[2], vals[1]
185 case 4:
186 top, right, bottom, left = vals[0], vals[1], vals[2], vals[3]
187 default:
188 panic(fmt.Sprintf("too many padding values: received %d, expected maximum of 4", len(args)))
189 }
190
191 return filter{
192 Options: newFilterOpts(_args...),
193 Filter: paddingFilter{
194 top: top,
195 right: right,
196 bottom: bottom,
197 left: left,
198 ccolor: ccolor,
199 },
200 }
201 }
202
203 // Dither creates a filter that dithers an image.
204 func (*Filters) Dither(options ...any) gift.Filter {
205 ditherOptions := struct {
206 Colors []any
207 Method string
208 Serpentine bool
209 Strength float32
210 }{
211 Method: "floydsteinberg",
212 Serpentine: true,
213 Strength: 1.0,
214 }
215
216 if len(options) != 0 {
217 err := mapstructure.WeakDecode(options[0], &ditherOptions)
218 if err != nil {
219 panic(fmt.Sprintf("failed to decode options: %s", err))
220 }
221 }
222
223 if len(ditherOptions.Colors) == 0 {
224 ditherOptions.Colors = []any{"000000ff", "ffffffff"}
225 }
226
227 if len(ditherOptions.Colors) < 2 {
228 panic("palette must have at least two colors")
229 }
230
231 var palette []color.Color
232 for _, c := range ditherOptions.Colors {
233 cc, ok, err := toColorGo(c)
234 if !ok || err != nil {
235 panic(fmt.Sprintf("%q is an invalid color: specify RGB or RGBA using hexadecimal notation", c))
236 }
237 palette = append(palette, cc)
238 }
239
240 d := dither.NewDitherer(palette)
241 if method, ok := ditherMethodsErrorDiffusion[strings.ToLower(ditherOptions.Method)]; ok {
242 d.Matrix = dither.ErrorDiffusionStrength(method, ditherOptions.Strength)
243 d.Serpentine = ditherOptions.Serpentine
244 } else if method, ok := ditherMethodsOrdered[strings.ToLower(ditherOptions.Method)]; ok {
245 d.Mapper = dither.PixelMapperFromMatrix(method, ditherOptions.Strength)
246 } else {
247 panic(fmt.Sprintf("%q is an invalid dithering method: see documentation", ditherOptions.Method))
248 }
249
250 return filter{
251 Options: newFilterOpts(ditherOptions),
252 Filter: ditherFilter{ditherer: d},
253 }
254 }
255
256 // AutoOrient creates a filter that rotates and flips an image as needed per
257 // its EXIF orientation tag.
258 func (*Filters) AutoOrient() gift.Filter {
259 return filter{
260 Filter: autoOrientFilter{},
261 }
262 }
263
264 // Brightness creates a filter that changes the brightness of an image.
265 // The percentage parameter must be in range (-100, 100).
266 func (*Filters) Brightness(percentage any) gift.Filter {
267 return filter{
268 Options: newFilterOpts(percentage),
269 Filter: gift.Brightness(cast.ToFloat32(percentage)),
270 }
271 }
272
273 // ColorBalance creates a filter that changes the color balance of an image.
274 // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500).
275 func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter {
276 return filter{
277 Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue),
278 Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)),
279 }
280 }
281
282 // Colorize creates a filter that produces a colorized version of an image.
283 // The hue parameter is the angle on the color wheel, typically in range (0, 360).
284 // The saturation parameter must be in range (0, 100).
285 // The percentage parameter specifies the strength of the effect, it must be in range (0, 100).
286 func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter {
287 return filter{
288 Options: newFilterOpts(hue, saturation, percentage),
289 Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)),
290 }
291 }
292
293 // Contrast creates a filter that changes the contrast of an image.
294 // The percentage parameter must be in range (-100, 100).
295 func (*Filters) Contrast(percentage any) gift.Filter {
296 return filter{
297 Options: newFilterOpts(percentage),
298 Filter: gift.Contrast(cast.ToFloat32(percentage)),
299 }
300 }
301
302 // Gamma creates a filter that performs a gamma correction on an image.
303 // The gamma parameter must be positive. Gamma = 1 gives the original image.
304 // Gamma less than 1 darkens the image and gamma greater than 1 lightens it.
305 func (*Filters) Gamma(gamma any) gift.Filter {
306 return filter{
307 Options: newFilterOpts(gamma),
308 Filter: gift.Gamma(cast.ToFloat32(gamma)),
309 }
310 }
311
312 // GaussianBlur creates a filter that applies a gaussian blur to an image.
313 func (*Filters) GaussianBlur(sigma any) gift.Filter {
314 return filter{
315 Options: newFilterOpts(sigma),
316 Filter: gift.GaussianBlur(cast.ToFloat32(sigma)),
317 }
318 }
319
320 // Grayscale creates a filter that produces a grayscale version of an image.
321 func (*Filters) Grayscale() gift.Filter {
322 return filter{
323 Filter: gift.Grayscale(),
324 }
325 }
326
327 // Hue creates a filter that rotates the hue of an image.
328 // The hue angle shift is typically in range -180 to 180.
329 func (*Filters) Hue(shift any) gift.Filter {
330 return filter{
331 Options: newFilterOpts(shift),
332 Filter: gift.Hue(cast.ToFloat32(shift)),
333 }
334 }
335
336 // Invert creates a filter that negates the colors of an image.
337 func (*Filters) Invert() gift.Filter {
338 return filter{
339 Filter: gift.Invert(),
340 }
341 }
342
343 // Pixelate creates a filter that applies a pixelation effect to an image.
344 func (*Filters) Pixelate(size any) gift.Filter {
345 return filter{
346 Options: newFilterOpts(size),
347 Filter: gift.Pixelate(cast.ToInt(size)),
348 }
349 }
350
351 // Saturation creates a filter that changes the saturation of an image.
352 func (*Filters) Saturation(percentage any) gift.Filter {
353 return filter{
354 Options: newFilterOpts(percentage),
355 Filter: gift.Saturation(cast.ToFloat32(percentage)),
356 }
357 }
358
359 // Sepia creates a filter that produces a sepia-toned version of an image.
360 func (*Filters) Sepia(percentage any) gift.Filter {
361 return filter{
362 Options: newFilterOpts(percentage),
363 Filter: gift.Sepia(cast.ToFloat32(percentage)),
364 }
365 }
366
367 // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image.
368 // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.
369 func (*Filters) Sigmoid(midpoint, factor any) gift.Filter {
370 return filter{
371 Options: newFilterOpts(midpoint, factor),
372 Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)),
373 }
374 }
375
376 // UnsharpMask creates a filter that sharpens an image.
377 // The sigma parameter is used in a gaussian function and affects the radius of effect.
378 // Sigma must be positive. Sharpen radius roughly equals 3 * sigma.
379 // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5.
380 // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.
381 func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter {
382 return filter{
383 Options: newFilterOpts(sigma, amount, threshold),
384 Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)),
385 }
386 }
387
388 type filter struct {
389 Options filterOpts
390 gift.Filter
391 }
392
393 // For cache-busting.
394 type filterOpts struct {
395 Version int
396 Vals any
397 }
398
399 func newFilterOpts(vals ...any) filterOpts {
400 return filterOpts{
401 Version: filterAPIVersion,
402 Vals: vals,
403 }
404 }