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