Debian Codegraph @

resources/images/config.go

raw
1 // Copyright 2019 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
15
16 import (
17 "errors"
18 "fmt"
19 "image/color"
20 "maps"
21 "slices"
22 "strconv"
23 "strings"
24
25 "github.com/gohugoio/hugo/common/hashing"
26 "github.com/gohugoio/hugo/common/hmaps"
27 "github.com/gohugoio/hugo/config"
28 "github.com/gohugoio/hugo/media"
29 "github.com/mitchellh/mapstructure"
30
31 "github.com/gohugoio/gift"
32 )
33
34 const (
35 ActionResize = "resize"
36 ActionCrop = "crop"
37 ActionFit = "fit"
38 ActionFill = "fill"
39 ActionFilter = "filter"
40 )
41
42 var Actions = map[string]bool{
43 ActionResize: true,
44 ActionCrop: true,
45 ActionFit: true,
46 ActionFill: true,
47 }
48
49 var (
50 imageFormats = map[string]Format{
51 ".jpg": JPEG,
52 ".jpeg": JPEG,
53 ".jpe": JPEG,
54 ".jif": JPEG,
55 ".jfif": JPEG,
56 ".png": PNG,
57 ".tif": TIFF,
58 ".tiff": TIFF,
59 ".bmp": BMP,
60 ".gif": GIF,
61 ".webp": WEBP,
62 ".avif": AVIF,
63 ".heif": HEIF,
64 ".heic": HEIC,
65 }
66
67 // These are the image types we can process.
68 processableImageSubTypes = map[string]Format{
69 media.Builtin.JPEGType.SubType: JPEG,
70 media.Builtin.PNGType.SubType: PNG,
71 media.Builtin.TIFFType.SubType: TIFF,
72 media.Builtin.BMPType.SubType: BMP,
73 media.Builtin.GIFType.SubType: GIF,
74 media.Builtin.WEBPType.SubType: WEBP,
75 media.Builtin.AVIFType.SubType: AVIF,
76 }
77
78 // We cannot process these formats, but we can provide metadata support for them (including width/height).
79 metaOnlyImageSubTypes = map[string]Format{
80 media.Builtin.AVIFType.SubType: AVIF,
81 media.Builtin.HEIFType.SubType: HEIF,
82 media.Builtin.HEICType.SubType: HEIC,
83 }
84
85 // Increment to mark all processed images as stale. Only use when absolutely needed.
86 // See the finer grained smartCropVersionNumber.
87 MainImageVersionNumber = 1
88
89 // Increment a format's version number to mark all processed images targeting
90 // that format as stale, e.g. after a change to its encoder. This is finer
91 // grained than mainImageVersionNumber, which invalidates every format.
92 FormatVersionNumbers = map[Format]int{
93 AVIF: 1,
94 PNG: 1, // See issue 12543, 12536
95 }
96 )
97
98 var anchorPositions = map[string]gift.Anchor{
99 strings.ToLower("Center"): gift.CenterAnchor,
100 strings.ToLower("TopLeft"): gift.TopLeftAnchor,
101 strings.ToLower("Top"): gift.TopAnchor,
102 strings.ToLower("TopRight"): gift.TopRightAnchor,
103 strings.ToLower("Left"): gift.LeftAnchor,
104 strings.ToLower("Right"): gift.RightAnchor,
105 strings.ToLower("BottomLeft"): gift.BottomLeftAnchor,
106 strings.ToLower("Bottom"): gift.BottomAnchor,
107 strings.ToLower("BottomRight"): gift.BottomRightAnchor,
108 smartCropIdentifier: SmartCropAnchor,
109 }
110
111 var compressionMethods = map[string]bool{
112 "lossy": true,
113 "lossless": true,
114 }
115
116 // These encoding hints are used by Webp (preset) and Avif (chroma subsampling).
117 var hints = map[string]bool{
118 "picture": true,
119 "photo": true,
120 "drawing": true,
121 "icon": true,
122 "text": true,
123 }
124
125 var imageFilters = map[string]gift.Resampling{
126 strings.ToLower("NearestNeighbor"): gift.NearestNeighborResampling,
127 strings.ToLower("Box"): gift.BoxResampling,
128 strings.ToLower("Linear"): gift.LinearResampling,
129 strings.ToLower("Hermite"): hermiteResampling,
130 strings.ToLower("MitchellNetravali"): mitchellNetravaliResampling,
131 strings.ToLower("CatmullRom"): catmullRomResampling,
132 strings.ToLower("BSpline"): bSplineResampling,
133 strings.ToLower("Gaussian"): gaussianResampling,
134 strings.ToLower("Lanczos"): gift.LanczosResampling,
135 strings.ToLower("Hann"): hannResampling,
136 strings.ToLower("Hamming"): hammingResampling,
137 strings.ToLower("Blackman"): blackmanResampling,
138 strings.ToLower("Bartlett"): bartlettResampling,
139 strings.ToLower("Welch"): welchResampling,
140 strings.ToLower("Cosine"): cosineResampling,
141 }
142
143 func ImageFormatFromExt(ext string) (Format, bool) {
144 f, found := imageFormats[ext]
145 return f, found
146 }
147
148 type ImageResourceType int
149
150 const (
151 // ImageResourceTypeNone means that the resource is not an image, and thus does not support any image operations.
152 ImageResourceTypeNone ImageResourceType = iota
153 // This is an image, but with no support for any image operations.
154 ImageResourceTypeBasic
155 // ImageResourceTypeMetaOnly means that only metadata operations (e.g. getting width/height and other metadata) are supported for this format.
156 ImageResourceTypeMetaOnly
157 // ImageResourceTypeProcessable means that all image operations (resizing, cropping, etc.) are supported for this format.
158 ImageResourceTypeProcessable
159 )
160
161 // ImageFormatFromMediaSubType returns the image format for the given media subtype, and how much image processing operations are supported for this format.
162 func ImageFormatFromMediaSubType(sub string) (Format, ImageResourceType) {
163 f, found := processableImageSubTypes[sub]
164 if found {
165 return f, ImageResourceTypeProcessable
166 }
167 if f, found = metaOnlyImageSubTypes[sub]; found {
168 return f, ImageResourceTypeMetaOnly
169 }
170 return f, ImageResourceTypeBasic
171 }
172
173 const (
174 defaultResampleFilter = "box"
175 defaultBgColor = "#ffffff"
176 defaultHint = "photo"
177 defaultCompression = "lossy"
178 defaultWebpUseSharpYuv = false
179 defaultWebpMethod = 2
180 defaultAvifEncoderSpeed = 10
181 )
182
183 func DecodeConfig(in map[string]any) (*config.ConfigNamespace[ImagingConfig, ImagingConfigInternal], error) {
184 if in == nil {
185 in = make(map[string]any)
186 }
187
188 buildConfig := func(in any) (ImagingConfigInternal, any, error) {
189 m, err := hmaps.ToStringMapE(in)
190 if err != nil {
191 return ImagingConfigInternal{}, nil, err
192 }
193
194 i := ImagingConfigInternal{
195 Imaging: ImagingConfig{
196 BgColor: defaultBgColor,
197 ResampleFilter: defaultResampleFilter,
198 Webp: WebpConfig{
199 UseSharpYuv: defaultWebpUseSharpYuv,
200 Method: defaultWebpMethod,
201 },
202 Avif: AvifConfig{
203 EncoderSpeed: defaultAvifEncoderSpeed,
204 },
205 },
206 }
207
208 if err := mapstructure.Decode(m, &i.Imaging); err != nil {
209 return i, nil, err
210 }
211
212 if err := i.Imaging.init(); err != nil {
213 return i, nil, err
214 }
215
216 i.BgColor, err = hexStringToColorGo(i.Imaging.BgColor)
217 if err != nil {
218 return i, nil, err
219 }
220
221 if i.Imaging.Anchor != "" {
222 anchor, found := anchorPositions[i.Imaging.Anchor]
223 if !found {
224 return i, nil, fmt.Errorf("invalid anchor value %q in imaging config", i.Imaging.Anchor)
225 }
226 i.Anchor = anchor
227 }
228
229 filter, found := imageFilters[i.Imaging.ResampleFilter]
230 if !found {
231 return i, nil, fmt.Errorf("%q is not a valid resample filter", filter)
232 }
233
234 i.ResampleFilter = filter
235
236 return i, i.Imaging, nil
237 }
238
239 ns, err := config.DecodeNamespace[ImagingConfig](in, buildConfig)
240 if err != nil {
241 return nil, err
242 }
243 return ns, nil
244 }
245
246 func DecodeImageConfig(options []string, defaults *config.ConfigNamespace[ImagingConfig, ImagingConfigInternal], sourceFormat Format) (ImageConfig, error) {
247 var (
248 c ImageConfig = newImageConfig()
249 err error
250 )
251
252 // Make to lower case, trim space and remove any empty strings.
253 n := 0
254 for _, s := range options {
255 s = strings.TrimSpace(s)
256 if s != "" {
257 options[n] = strings.ToLower(s)
258 n++
259 }
260 }
261 options = options[:n]
262
263 for _, part := range options {
264 if _, ok := Actions[part]; ok {
265 c.Action = part
266 } else if pos, ok := anchorPositions[part]; ok {
267 c.Anchor = pos
268 } else if filter, ok := imageFilters[part]; ok {
269 c.Filter = filter
270 } else if _, ok := hints[part]; ok {
271 c.Hint = part
272 } else if _, ok := compressionMethods[part]; ok {
273 c.Compression = part
274 } else if f, ok := ImageFormatFromExt("." + part); ok {
275 c.TargetFormat = f
276 } else if part[0] == '#' {
277 c.BgColor, err = hexStringToColorGo(part[1:])
278 if err != nil {
279 return c, err
280 }
281 } else if part[0] == 'q' {
282 c.Quality, err = strconv.Atoi(part[1:])
283 if err != nil {
284 return c, err
285 }
286 if c.Quality < 1 || c.Quality > 100 {
287 return c, errors.New("quality ranges from 1 to 100 inclusive")
288 }
289 } else if part[0] == 'r' {
290 c.Rotate, err = strconv.Atoi(part[1:])
291 if err != nil {
292 return c, err
293 }
294 } else if strings.Contains(part, "x") {
295 widthHeight := strings.Split(part, "x")
296 if len(widthHeight) <= 2 {
297 first := widthHeight[0]
298 if first != "" {
299 c.Width, err = strconv.Atoi(first)
300 if err != nil {
301 return c, err
302 }
303 }
304
305 if len(widthHeight) == 2 {
306 second := widthHeight[1]
307 if second != "" {
308 c.Height, err = strconv.Atoi(second)
309 if err != nil {
310 return c, err
311 }
312 }
313 }
314 } else {
315 return c, errors.New("invalid image dimensions")
316 }
317 }
318 }
319
320 switch c.Action {
321 case ActionCrop, ActionFill, ActionFit:
322 if c.Width == 0 || c.Height == 0 {
323 return c, errors.New("must provide Width and Height")
324 }
325 case ActionResize:
326 if c.Width == 0 && c.Height == 0 {
327 return c, errors.New("must provide Width or Height")
328 }
329 default:
330 if c.Width != 0 || c.Height != 0 {
331 return c, errors.New("width or height are not supported for this action")
332 }
333 }
334
335 if err := c.init(defaults.Config, sourceFormat); err != nil {
336 return c, err
337 }
338
339 if MainImageVersionNumber > 0 {
340 options = append(options, strconv.Itoa(MainImageVersionNumber))
341 }
342
343 if v := FormatVersionNumbers[c.TargetFormat]; v > 0 {
344 options = append(options, "tfv"+strconv.Itoa(v))
345 }
346
347 usesSmartCrop := c.Anchor == SmartCropAnchor && (c.Action == ActionCrop || c.Action == ActionFill)
348 if smartCropVersionNumber > 0 && usesSmartCrop {
349 options = append(options, strconv.Itoa(smartCropVersionNumber))
350 }
351
352 c.Key = hashing.HashStringHex(options)
353
354 return c, nil
355 }
356
357 // ImageConfig holds configuration to create a new image from an existing one, resize etc.
358 type ImageConfig struct {
359 // This defines the output format of the output image. It defaults to the source format.
360 TargetFormat Format
361
362 // Optional image processing action to perform ("resize", "crop", "fit", "fill"). When empty, the operation may still perform e.g. format conversion.
363 Action string
364
365 // If set, this will be used as the key in filenames etc.
366 Key string
367
368 // Whether the palette of a paletted source image should be re-applied to
369 // the result when the target format is PNG, so an indexed PNG stays indexed.
370 // This is always the case for the geometric actions (resize, crop, fit, fill);
371 // a filter chain turns it off unless all its filters are geometric,
372 // as other filters routinely introduce colors outside the source palette.
373 // See issue 12543.
374 PreserveSourcePalette bool
375
376 // Quality ranges from 1 to 100 inclusive, higher is better.
377 // This is only relevant for JPEG and WEBP images.
378 // For WEBP it's only relevant for lossy encoding.
379 // Default is 75.
380 Quality int
381
382 // Rotate rotates an image by the given angle counter-clockwise.
383 // The rotation will be performed first.
384 Rotate int
385
386 // Used to fill any transparency.
387 // When set in project config, it's used when converting to a format that does
388 // not support transparency.
389 // When set per image operation, it's used even for formats that does support
390 // transparency.
391 BgColor color.Color
392
393 Filter gift.Resampling
394 Anchor gift.Anchor
395
396 // Hint about what type of picture this is. Used to optimize encoding
397 // when target is webp (preset) or avif (chroma subsampling).
398 Hint string
399
400 Compression string
401
402 // WebP-specific options.
403 UseSharpYuv bool
404 Method int
405
406 // AVIF-specific options.
407 EncoderSpeed int
408
409 Width int
410 Height int
411 }
412
413 func (c *ImageConfig) init(defaults ImagingConfigInternal, sourceFormat Format) error {
414 if c.Action != "" && c.Anchor == -1 {
415 c.Anchor = defaults.Anchor
416 }
417 if c.TargetFormat == 0 {
418 c.TargetFormat = sourceFormat
419 }
420 if c.Filter == nil {
421 c.Filter = defaults.ResampleFilter
422 }
423 if c.Anchor == -1 {
424 c.Anchor = defaults.Anchor
425 }
426 if c.Hint == "" {
427 c.Hint = defaults.Imaging.hintFor(c.TargetFormat)
428 }
429
430 if c.Quality == 0 {
431 c.Quality = defaults.Imaging.qualityFor(c.TargetFormat)
432 }
433
434 if c.Compression == "" {
435 c.Compression = defaults.Imaging.compressionFor(c.TargetFormat)
436 }
437
438 if c.TargetFormat == AVIF {
439 c.EncoderSpeed = defaults.Imaging.Avif.EncoderSpeed
440 }
441
442 if c.TargetFormat == WEBP {
443 c.Method = defaults.Imaging.Webp.Method
444 c.UseSharpYuv = defaults.Imaging.Webp.UseSharpYuv
445 }
446
447 if c.BgColor == nil && c.TargetFormat != sourceFormat {
448 if sourceFormat.SupportsTransparency() && !c.TargetFormat.SupportsTransparency() {
449 c.BgColor = defaults.BgColor
450 }
451 }
452 return nil
453 }
454
455 func (c ImageConfig) Reanchor(a gift.Anchor) ImageConfig {
456 c.Anchor = a
457 c.Key = hashing.HashStringHex(c.Key, "reanchor", a)
458 return c
459 }
460
461 type ImagingConfigInternal struct {
462 BgColor color.Color
463 ResampleFilter gift.Resampling
464 Anchor gift.Anchor
465
466 Imaging ImagingConfig
467 }
468
469 func (i *ImagingConfigInternal) Compile(externalCfg *ImagingConfig) error {
470 var err error
471 i.BgColor, err = hexStringToColorGo(externalCfg.BgColor)
472 if err != nil {
473 return err
474 }
475
476 if externalCfg.Anchor != "" {
477 anchor, found := anchorPositions[externalCfg.Anchor]
478 if !found {
479 return fmt.Errorf("invalid anchor value %q in imaging config", externalCfg.Anchor)
480 }
481 i.Anchor = anchor
482 }
483
484 filter, found := imageFilters[externalCfg.ResampleFilter]
485 if !found {
486 return fmt.Errorf("%q is not a valid resample filter", externalCfg.ResampleFilter)
487 }
488 i.ResampleFilter = filter
489
490 return nil
491 }
492
493 // ImagingConfig contains default image processing configuration. This will be fetched
494 // from site (or language) config.
495 type ImagingConfig struct {
496 // Default image quality setting (1-100). Used as the fallback for JPEG,
497 // WebP and AVIF when no per-format quality is set. When left unset, JPEG
498 // and WebP default to 75 and AVIF to 60 (its scale differs perceptually).
499 // Deprecated in v0.163.0: set the quality per format instead, see
500 // imaging.jpeg.quality, imaging.webp.quality and imaging.avif.quality.
501 Quality int `json:"-"`
502
503 // Compression method to use.
504 // One of "lossy" or "lossless".
505 // Note that lossless is currently only supported for WebP and AVIF.
506 // Deprecated in v0.163.0: set the compression method per format instead, see imaging.webp.compression and imaging.avif.compression.
507 Compression string `json:"-"`
508
509 // Resample filter to use in resize operations.
510 ResampleFilter string
511
512 // Hint about what type of image this is.
513 // Used when encoding to Webp (preset) and Avif (chroma subsampling).
514 // Default is "photo".
515 // Valid values are "picture", "photo", "drawing", "icon", or "text".
516 // Moved to WebpConfig in v0.155.0, but kept here for backwards compatibility.
517 Hint string `json:"-"`
518
519 // The anchor to use in Fill. Default is "smart", i.e. Smart Crop.
520 Anchor string
521
522 // Default color used in fill operations (e.g. "fff" for white).
523 BgColor string
524
525 Exif ExifConfig
526 Meta MetaConfig
527 Jpeg JpegConfig
528 Webp WebpConfig
529 Avif AvifConfig
530 }
531
532 func (cfg *ImagingConfig) qualityFor(f Format) int {
533 switch f {
534 case JPEG:
535 return cfg.Jpeg.Quality
536 case WEBP:
537 return cfg.Webp.Quality
538 case AVIF:
539 return cfg.Avif.Quality
540 }
541 return 0
542 }
543
544 func (cfg *ImagingConfig) compressionFor(f Format) string {
545 switch f {
546 case WEBP:
547 return cfg.Webp.Compression
548 case AVIF:
549 return cfg.Avif.Compression
550 }
551 return ""
552 }
553
554 // hintFor returns the configured hint for the given target format.
555 func (cfg *ImagingConfig) hintFor(f Format) string {
556 switch f {
557 case WEBP:
558 return cfg.Webp.Hint
559 case AVIF:
560 return cfg.Avif.Hint
561 }
562 return ""
563 }
564
565 var validMetaSources = map[string]bool{
566 "exif": true,
567 "iptc": true,
568 "xmp": true,
569 }
570
571 func (cfg *ImagingConfig) init() error {
572 cfg.BgColor = strings.ToLower(strings.TrimPrefix(cfg.BgColor, "#"))
573 cfg.Anchor = strings.ToLower(cfg.Anchor)
574 cfg.ResampleFilter = strings.ToLower(cfg.ResampleFilter)
575 cfg.Hint = strings.ToLower(cfg.Hint)
576 cfg.Compression = strings.ToLower(cfg.Compression)
577 if err := cfg.Jpeg.init(cfg); err != nil {
578 return fmt.Errorf("invalid jpeg config: %w", err)
579 }
580 if err := cfg.Webp.init(cfg); err != nil {
581 return fmt.Errorf("invalid webp config: %w", err)
582 }
583 if err := cfg.Avif.init(cfg); err != nil {
584 return fmt.Errorf("invalid avif config: %w", err)
585 }
586 if cfg.Quality < 0 || cfg.Quality > 100 {
587 return fmt.Errorf("imaging.quality must be between 1 and 100 inclusive, got %d", cfg.Quality)
588 }
589
590 if cfg.Anchor == "" {
591 cfg.Anchor = smartCropIdentifier
592 }
593
594 if strings.TrimSpace(cfg.Exif.IncludeFields) == "" && strings.TrimSpace(cfg.Exif.ExcludeFields) == "" {
595 // Don't change this for no good reason. Please don't.
596 cfg.Exif.ExcludeFields = "GPS|Exif|Exposure[M|P|B]|Contrast|Resolution|Sharp|JPEG|Metering|Sensing|Saturation|ColorSpace|Flash|WhiteBalance"
597 }
598
599 if len(cfg.Meta.Fields) == 0 {
600 // Default: include all fields except technical metadata.
601 // Don't change this for no good reason. Please don't.
602 cfg.Meta.Fields = []string{
603 "! *{GPS,Exif,Exposure[MPB],Contrast,Resolution,Sharp,JPEG,Metering,Sensing,Saturation,ColorSpace,Flash,WhiteBalance}*",
604 }
605 }
606
607 if len(cfg.Meta.Sources) == 0 {
608 // Default to EXIF and IPTC (XMP is slower to decode).
609 cfg.Meta.Sources = []string{"exif", "iptc"}
610 } else {
611 // Normalize to lowercase.
612 for i, s := range cfg.Meta.Sources {
613 cfg.Meta.Sources[i] = strings.ToLower(s)
614 if !validMetaSources[cfg.Meta.Sources[i]] {
615 keys := slices.Collect(maps.Keys(validMetaSources))
616 slices.Sort(keys)
617 return fmt.Errorf("invalid metadata source %q in imaging.meta.sources config; must be one of %s", s, keys)
618 }
619 }
620 }
621
622 return nil
623 }
624
625 type ExifConfig struct {
626 // Regexp matching the Exif fields you want from the (massive) set of Exif info
627 // available. As we cache this info to disk, this is for performance and
628 // disk space reasons more than anything.
629 // If you want it all, put ".*" in this config setting.
630 // Note that if neither this or ExcludeFields is set, Hugo will return a small
631 // default set.
632 IncludeFields string
633
634 // Regexp matching the Exif fields you want to exclude. This may be easier to use
635 // than IncludeFields above, depending on what you want.
636 ExcludeFields string
637
638 // Hugo extracts the "photo taken" date/time into .Date by default.
639 // Set this to true to turn it off.
640 DisableDate bool
641
642 // Hugo extracts the "photo taken where" (GPS latitude and longitude) into
643 // .Long and .Lat. Set this to true to turn it off.
644 DisableLatLong bool
645 }
646
647 type MetaConfig struct {
648 // Glob patterns for which metadata fields to include.
649 // Use "! " prefix to exclude patterns (e.g., "! *GPS*" excludes GPS fields).
650 // Patterns are OR'd together for inclusion, AND'd for exclusion.
651 // If empty, a default set excluding technical metadata is used.
652 // Use ["**"] to include all fields.
653 Fields []string
654
655 // Which metadata sources to include.
656 // Valid values are "exif", "iptc", "xmp".
657 // Default is ["exif", "iptc"] (XMP is excluded for performance reasons).
658 Sources []string
659 }
660
661 // JpegConfig holds JPEG-specific encoding configuration.
662 type JpegConfig struct {
663 // Quality setting (1-100). Falls back to the global imaging.quality if unset.
664 Quality int
665 }
666
667 func (c *JpegConfig) init(ic *ImagingConfig) error {
668 if c.Quality == 0 {
669 c.Quality = ic.Quality
670 }
671 if c.Quality == 0 {
672 c.Quality = 75
673 }
674 if c.Quality < 1 || c.Quality > 100 {
675 return fmt.Errorf("imaging.jpeg.quality must be between 1 and 100 inclusive, got %d", c.Quality)
676 }
677 return nil
678 }
679
680 // AvifConfig holds AVIF-specific encoding configuration.
681 type AvifConfig struct {
682 // Quality setting (1-100). Falls back to the global imaging.quality if unset.
683 Quality int
684
685 // Compression method to use.
686 // One of "lossy" or "lossless".
687 Compression string
688
689 // Hint about what type of image this is. Used for chroma subsampling.
690 // Valid values are "picture", "photo", "drawing", "icon", or "text".
691 // Default is "photo".
692 Hint string
693
694 // Encoder quality/speed trade-off, 1 (slowest, best quality / smallest
695 // files) to 10 (fastest). Default is 10 — fast enough for incremental
696 // builds with quality indistinguishable from slower settings at typical
697 // web thumbnail sizes. Lower values reduce file size at the cost of
698 // build time.
699 // We recommend sticking with the default of 10 unless you have a specific reason to change it,
700 // and to stay above 5 to avoid very long build times and timeouts.
701 EncoderSpeed int
702 }
703
704 func (c *AvifConfig) init(ic *ImagingConfig) error {
705 if c.Hint == "" {
706 c.Hint = ic.Hint
707 }
708 if c.Compression == "" {
709 c.Compression = ic.Compression
710 }
711 if c.Quality == 0 {
712 c.Quality = ic.Quality
713 }
714 if c.Hint == "" {
715 c.Hint = defaultHint
716 }
717 if c.Compression == "" {
718 c.Compression = defaultCompression
719 }
720 if c.Quality == 0 {
721 c.Quality = 60
722 }
723
724 c.Hint = strings.ToLower(c.Hint)
725 c.Compression = strings.ToLower(c.Compression)
726
727 if c.Hint != "" && !hints[c.Hint] {
728 return fmt.Errorf("imaging.avif.hint must be one of picture, photo, drawing, icon, or text, got %q", c.Hint)
729 }
730 if c.EncoderSpeed < 1 || c.EncoderSpeed > 10 {
731 return fmt.Errorf("imaging.avif.encoderSpeed must be between 1 and 10, got %d", c.EncoderSpeed)
732 }
733
734 if c.Compression != "" && !compressionMethods[c.Compression] {
735 return fmt.Errorf("imaging.avif.compression must be one of lossy or lossless, got %q", c.Compression)
736 }
737 if c.Quality < 1 || c.Quality > 100 {
738 return fmt.Errorf("imaging.avif.quality must be between 1 and 100 inclusive, got %d", c.Quality)
739 }
740
741 return nil
742 }
743
744 // WebpConfig holds WebP-specific encoding configuration.
745 type WebpConfig struct {
746 // Quality setting (1-100). Falls back to the global imaging.quality if unset.
747 // Only relevant for lossy encoding.
748 Quality int
749
750 // Compression method to use.
751 // One of "lossy" or "lossless".
752 Compression string
753
754 // Hint about what type of image this is.
755 // Valid values are "picture", "photo", "drawing", "icon", or "text".
756 // Default is "photo".
757 Hint string
758
759 // Use sharp (and slow) RGB->YUV conversion.
760 // Default is true.
761 UseSharpYuv bool
762
763 // Quality/speed trade-off (0=fast, 6=slower-better).
764 // Default is 2.
765 Method int
766 }
767
768 func (c *WebpConfig) init(ic *ImagingConfig) error {
769 if c.Hint == "" {
770 c.Hint = ic.Hint
771 }
772 if c.Compression == "" {
773 c.Compression = ic.Compression
774 }
775 if c.Quality == 0 {
776 c.Quality = ic.Quality
777 }
778 if c.Hint == "" {
779 c.Hint = defaultHint
780 }
781 if c.Compression == "" {
782 c.Compression = defaultCompression
783 }
784 if c.Quality == 0 {
785 c.Quality = 75
786 }
787
788 c.Hint = strings.ToLower(c.Hint)
789 c.Compression = strings.ToLower(c.Compression)
790
791 if c.Hint != "" && !hints[c.Hint] {
792 return fmt.Errorf("imaging.webp.hint must be one of picture, photo, drawing, icon, or text, got %q", c.Hint)
793 }
794 if c.Method < 0 || c.Method > 6 {
795 return fmt.Errorf("imaging.webp.method must be between 0 and 6, got %d", c.Method)
796 }
797 if c.Compression != "" && !compressionMethods[c.Compression] {
798 return fmt.Errorf("imaging.webp.compression must be one of lossy or lossless, got %q", c.Compression)
799 }
800 if c.Quality < 1 || c.Quality > 100 {
801 return fmt.Errorf("imaging.webp.quality must be between 1 and 100 inclusive, got %d", c.Quality)
802 }
803 return nil
804 }