Debian Codegraph @

resources/images/image.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"
20 "image/color"
21 "image/draw"
22 "io"
23 "sync"
24
25 "github.com/bep/imagemeta"
26 "github.com/bep/logg"
27 "github.com/gohugoio/hugo/config"
28 "github.com/gohugoio/hugo/internal/warpc"
29
30 "github.com/gohugoio/hugo/media"
31 "github.com/gohugoio/hugo/resources/images/meta"
32
33 "github.com/gohugoio/gift"
34
35 "github.com/gohugoio/hugo/common/himage"
36 "github.com/gohugoio/hugo/common/hugio"
37 )
38
39 func NewImage(f Format, proc *ImageProcessor, img image.Image, s Spec) *Image {
40 if img != nil {
41 return &Image{
42 Format: f,
43 Proc: proc,
44 Spec: s,
45 imageConfig: &imageConfig{
46 config: imageConfigFromImage(img),
47 configLoaded: true,
48 },
49 }
50 }
51 return &Image{Format: f, Proc: proc, Spec: s, imageConfig: &imageConfig{}}
52 }
53
54 type Image struct {
55 Format Format
56 Proc *ImageProcessor
57 Spec Spec
58 *imageConfig
59 }
60
61 func (i *Image) EncodeTo(conf ImageConfig, img image.Image, w io.Writer) error {
62 return i.Proc.Codec.EncodeTo(conf, w, img)
63 }
64
65 // Height returns i's height.
66 func (i *Image) Height() int {
67 i.initConfig()
68 return i.config.Height
69 }
70
71 // Width returns i's width.
72 func (i *Image) Width() int {
73 i.initConfig()
74 return i.config.Width
75 }
76
77 func (i Image) WithImage(img image.Image) *Image {
78 i.Spec = nil
79 i.imageConfig = &imageConfig{
80 config: imageConfigFromImage(img),
81 configLoaded: true,
82 }
83
84 return &i
85 }
86
87 func (i Image) WithSpec(s Spec) *Image {
88 i.Spec = s
89 i.imageConfig = &imageConfig{}
90 return &i
91 }
92
93 // InitConfig reads the image config from the given reader.
94 func (i *Image) InitConfig(r io.Reader) error {
95 var err error
96 i.configInit.Do(func() {
97 i.config, _, err = i.Proc.Codec.DecodeConfig(i.Format, r)
98 })
99 return err
100 }
101
102 func (i *Image) initConfig() {
103 var err error
104 i.configInit.Do(func() {
105 if i.configLoaded {
106 return
107 }
108
109 var f hugio.ReadSeekCloser
110
111 f, err = i.Spec.ReadSeekCloser()
112 if err != nil {
113 return
114 }
115 defer f.Close()
116
117 i.config, _, err = i.Proc.Codec.DecodeConfig(i.Format, f)
118 })
119
120 if err != nil {
121 panic(fmt.Errorf("failed to load image config: %w", err))
122 }
123 }
124
125 func NewImageProcessor(debugl, warnl logg.LevelLogger, wasmDispatchers *warpc.Dispatchers, cfg *config.ConfigNamespace[ImagingConfig, ImagingConfigInternal]) (*ImageProcessor, error) {
126 e := cfg.Config.Imaging.Exif
127 exifDecoder, err := meta.NewDecoder(
128 meta.WithDateDisabled(e.DisableDate),
129 meta.WithLatLongDisabled(e.DisableLatLong),
130 meta.ExcludeFields(e.ExcludeFields),
131 meta.IncludeFields(e.IncludeFields),
132 meta.WithWarnLogger(warnl),
133 )
134 if err != nil {
135 return nil, err
136 }
137
138 m := cfg.Config.Imaging.Meta
139 metaDecoder, err := meta.NewDecoder(
140 meta.WithFields(m.Fields),
141 meta.WithSources(m.Sources...),
142 meta.WithWarnLogger(warnl),
143 )
144 if err != nil {
145 return nil, err
146 }
147
148 webpCodec, err := wasmDispatchers.NewWepCodec()
149 if err != nil {
150 return nil, err
151 }
152 if webpCodec == nil {
153 return nil, errors.New("webp codec is not available")
154 }
155 avifCodec, err := wasmDispatchers.NewAvifCodec()
156 if err != nil {
157 return nil, err
158 }
159 imageCodec := newCodec(webpCodec, avifCodec, debugl)
160
161 return &ImageProcessor{
162 Cfg: cfg,
163 exifDecoder: exifDecoder,
164 metaDecoder: metaDecoder,
165 Codec: imageCodec,
166 }, nil
167 }
168
169 type ImageProcessor struct {
170 Cfg *config.ConfigNamespace[ImagingConfig, ImagingConfigInternal]
171 exifDecoder *meta.Decoder
172 metaDecoder *meta.Decoder
173 Codec *Codec
174 }
175
176 // Filename is only used for logging.
177 func (p *ImageProcessor) DecodeExif(filename string, format imagemeta.ImageFormat, r io.Reader) (*meta.ExifInfo, error) {
178 return p.exifDecoder.Decode(filename, format, r)
179 }
180
181 // DecodeMeta decodes metadata from configured sources.
182 // Filename is only used for logging.
183 func (p *ImageProcessor) DecodeMeta(filename string, format imagemeta.ImageFormat, r io.Reader) (*meta.MetaInfo, error) {
184 return p.metaDecoder.DecodeMeta(filename, format, r)
185 }
186
187 func (p *ImageProcessor) FiltersFromConfig(src image.Image, conf ImageConfig) ([]gift.Filter, error) {
188 var filters []gift.Filter
189
190 if conf.Rotate != 0 {
191 // Apply any rotation before any resize.
192 rotate := gift.Rotate(float32(conf.Rotate), color.Transparent, gift.NearestNeighborInterpolation)
193 filters = append(filters, rotate)
194 if conf.usesSmartCrop() {
195 // Smart crop must analyze the image in the orientation the crop is applied to.
196 rotated := image.NewNRGBA(rotate.Bounds(src.Bounds()))
197 gift.New(rotate).Draw(rotated, src)
198 src = rotated
199 }
200 }
201
202 switch conf.Action {
203 case "resize":
204 filters = append(filters, gift.Resize(conf.Width, conf.Height, conf.Filter))
205 case "crop":
206 if conf.Anchor == SmartCropAnchor {
207 bounds, err := p.smartCrop(src, conf.Width, conf.Height, conf.Filter)
208 if err != nil {
209 return nil, err
210 }
211
212 // First crop using the bounds returned by smartCrop.
213 filters = append(filters, gift.Crop(bounds))
214 // Then center crop the image to get an image the desired size without resizing.
215 filters = append(filters, gift.CropToSize(conf.Width, conf.Height, gift.CenterAnchor))
216
217 } else {
218 filters = append(filters, gift.CropToSize(conf.Width, conf.Height, conf.Anchor))
219 }
220 case "fill":
221 if conf.Anchor == SmartCropAnchor {
222 bounds, err := p.smartCrop(src, conf.Width, conf.Height, conf.Filter)
223 if err != nil {
224 return nil, err
225 }
226
227 // First crop it, then resize it.
228 filters = append(filters, gift.Crop(bounds))
229 filters = append(filters, gift.Resize(conf.Width, conf.Height, conf.Filter))
230
231 } else {
232 filters = append(filters, gift.ResizeToFill(conf.Width, conf.Height, conf.Filter, conf.Anchor))
233 }
234 case "fit":
235 filters = append(filters, gift.ResizeToFit(conf.Width, conf.Height, conf.Filter))
236 default:
237
238 }
239 return filters, nil
240 }
241
242 func (p *ImageProcessor) ApplyFiltersFromConfig(src image.Image, conf ImageConfig) (image.Image, error) {
243 filters, err := p.FiltersFromConfig(src, conf)
244 if err != nil {
245 return nil, err
246 }
247
248 if len(filters) == 0 {
249 return p.resolveSrc(src, conf.TargetFormat), nil
250 }
251
252 img, err := p.doFilter(src, conf.TargetFormat, filters...)
253 if err != nil {
254 return nil, err
255 }
256
257 return img, nil
258 }
259
260 func (p *ImageProcessor) Filter(src image.Image, filters ...gift.Filter) (image.Image, error) {
261 return p.doFilter(src, 0, filters...)
262 }
263
264 func (p *ImageProcessor) resolveSrc(src image.Image, targetFormat Format) image.Image {
265 if animatedImage, ok := src.(himage.AnimatedImage); ok {
266 frames := animatedImage.GetFrames()
267 // If e.g. converting an animated GIF to JPEG, we only want the first frame.
268 // Preserve the AnimatedImage wrapper for color properties only when there is
269 // no actual animation to preserve. Multi-frame animated sources must still be
270 // collapsed unless the target format supports animation output.
271 shouldExtractFirstFrame := len(frames) < 2 || !targetFormat.SupportsAnimation()
272 colorPropsNeedPreserving := himage.HasColorProperties(src) && len(frames) < 2
273 if shouldExtractFirstFrame && !colorPropsNeedPreserving {
274 src = frames[0]
275 }
276 }
277 return src
278 }
279
280 func (p *ImageProcessor) doFilter(src image.Image, targetFormat Format, filters ...gift.Filter) (image.Image, error) {
281 filter := gift.New(filters...)
282
283 if anim, ok := src.(himage.AnimatedImage); ok {
284 frames := anim.GetFrames()
285 // Check if we should extract first frame or preserve AnimatedImage wrapper.
286 // Preserve AnimatedImage if color properties need to be maintained.
287 shouldExtractFirstFrame := len(frames) < 2 || !targetFormat.SupportsAnimation()
288 colorPropsNeedPreserving := himage.HasColorProperties(src) && len(frames) < 2
289 if shouldExtractFirstFrame && !colorPropsNeedPreserving {
290 src = frames[0]
291 } else {
292 var bounds image.Rectangle
293 firstFrame := frames[0]
294 // Preserve bit depth for HDR images.
295 var tmp draw.Image
296 switch firstFrame.(type) {
297 case *image.RGBA64, *image.NRGBA64:
298 tmp = image.NewNRGBA64(firstFrame.Bounds())
299 default:
300 tmp = image.NewNRGBA(firstFrame.Bounds())
301 }
302 for i, frame := range frames {
303 gift.New().DrawAt(tmp, frame, frame.Bounds().Min, gift.OverOperator)
304 bounds = filter.Bounds(tmp.Bounds())
305 var dst draw.Image
306 switch f := frame.(type) {
307 case *image.Paletted:
308 // Gif.
309 dst = image.NewPaletted(bounds, f.Palette)
310 case *image.RGBA64:
311 dst = image.NewRGBA64(bounds)
312 case *image.NRGBA64:
313 dst = image.NewNRGBA64(bounds)
314 default:
315 dst = image.NewNRGBA(bounds)
316 }
317 filter.Draw(dst, tmp)
318 frames[i] = dst
319 }
320 anim.SetWidthHeight(bounds.Dx(), bounds.Dy())
321 anim.SetFrames(frames)
322
323 return anim, nil
324 }
325
326 }
327
328 bounds := filter.Bounds(src.Bounds())
329
330 var dst draw.Image
331 switch src.(type) {
332 case *image.RGBA:
333 dst = image.NewRGBA(bounds)
334 case *image.NRGBA:
335 dst = image.NewNRGBA(bounds)
336 case *image.Gray:
337 dst = image.NewGray(bounds)
338 case *image.RGBA64:
339 dst = image.NewRGBA64(bounds)
340 case *image.NRGBA64:
341 dst = image.NewNRGBA64(bounds)
342 case *image.Gray16:
343 dst = image.NewGray16(bounds)
344 default:
345 dst = image.NewNRGBA(bounds)
346 }
347 filter.Draw(dst, src)
348
349 return dst, nil
350 }
351
352 func newImageConfig() ImageConfig {
353 return ImageConfig{
354 Anchor: -1, // The real values start at 0.
355 PreserveSourcePalette: true,
356 }
357 }
358
359 type Spec interface {
360 // Loads the image source.
361 ReadSeekCloser() (hugio.ReadSeekCloser, error)
362 }
363
364 // Format is an image file format.
365 type Format int
366
367 const (
368 JPEG Format = iota + 1
369 PNG
370 GIF
371 TIFF
372 BMP
373 WEBP
374 AVIF
375
376 // Below: We have no encoder/decoder for these, but we can provide metadata support for them (including width/height).
377 HEIF
378 HEIC
379 )
380
381 // Whether to use imagemeta to decode image config (width/height ).
382 func (f Format) UseImageMetaConfigDecoder() bool {
383 return f == WEBP || f == AVIF || f == HEIF || f == HEIC
384 }
385
386 func (f Format) ToImageMetaImageFormatFormat() imagemeta.ImageFormat {
387 switch f {
388 case JPEG:
389 return imagemeta.JPEG
390 case PNG:
391 return imagemeta.PNG
392 case TIFF:
393 return imagemeta.TIFF
394 case WEBP:
395 return imagemeta.WebP
396 case AVIF:
397 return imagemeta.AVIF
398 case HEIF:
399 return imagemeta.HEIF
400 case HEIC:
401 return imagemeta.HEIF
402 default:
403 return -1
404 }
405 }
406
407 // SupportsTransparency reports whether it supports transparency in any form.
408 func (f Format) SupportsTransparency() bool {
409 return f != JPEG
410 }
411
412 // SupportsAnimation reports whether the format supports animation.
413 // AVIF supports animation in the spec, but Hugo's AVIF encoder is single-frame
414 // only — including AVIF here would make the pipeline preserve frames just to
415 // drop them at encode time.
416 func (f Format) SupportsAnimation() bool {
417 return f == GIF || f == WEBP
418 }
419
420 // DefaultExtension returns the default file extension of this format, starting with a dot.
421 // For example: .jpg for JPEG
422 func (f Format) DefaultExtension() string {
423 return f.MediaType().FirstSuffix.FullSuffix
424 }
425
426 // MediaType returns the media type of this image, e.g. image/jpeg for JPEG
427 func (f Format) MediaType() media.Type {
428 switch f {
429 case JPEG:
430 return media.Builtin.JPEGType
431 case PNG:
432 return media.Builtin.PNGType
433 case GIF:
434 return media.Builtin.GIFType
435 case TIFF:
436 return media.Builtin.TIFFType
437 case BMP:
438 return media.Builtin.BMPType
439 case WEBP:
440 return media.Builtin.WEBPType
441 case AVIF:
442 return media.Builtin.AVIFType
443 case HEIF:
444 return media.Builtin.HEIFType
445 case HEIC:
446 return media.Builtin.HEICType
447 default:
448 panic(fmt.Sprintf("%d is not a valid image format", f))
449 }
450 }
451
452 func (f Format) String() string {
453 switch f {
454 case JPEG:
455 return "JPEG"
456 case PNG:
457 return "PNG"
458 case GIF:
459 return "GIF"
460 case TIFF:
461 return "TIFF"
462 case BMP:
463 return "BMP"
464 case WEBP:
465 return "WEBP"
466 case AVIF:
467 return "AVIF"
468 case HEIF:
469 return "HEIF"
470 case HEIC:
471 return "HEIC"
472 default:
473 return "Unknown"
474 }
475 }
476
477 type imageConfig struct {
478 config image.Config
479 configInit sync.Once
480 configLoaded bool
481 }
482
483 func imageConfigFromImage(img image.Image) image.Config {
484 if cp, ok := img.(himage.ImageConfigProvider); ok {
485 return cp.GetImageConfig()
486 }
487 b := img.Bounds()
488 return image.Config{Width: b.Max.X, Height: b.Max.Y}
489 }
490
491 // UnwrapFilter unwraps the given filter if it is a filter wrapper.
492 func UnwrapFilter(in gift.Filter) gift.Filter {
493 if f, ok := in.(filter); ok {
494 return f.Filter
495 }
496 return in
497 }
498
499 // ToFilters converts the given input to a slice of gift.Filter.
500 func ToFilters(in any) []gift.Filter {
501 switch v := in.(type) {
502 case []gift.Filter:
503 return v
504 case []filter:
505 vv := make([]gift.Filter, len(v))
506 for i, f := range v {
507 vv[i] = f
508 }
509 return vv
510 case gift.Filter:
511 return []gift.Filter{v}
512 default:
513 panic(fmt.Sprintf("%T is not an image filter", in))
514 }
515 }
516
517 // IsOpaque returns false if the image has alpha channel and there is at least 1
518 // pixel that is not (fully) opaque.
519 func IsOpaque(img image.Image) bool {
520 if oim, ok := img.(interface {
521 Opaque() bool
522 }); ok {
523 return oim.Opaque()
524 }
525
526 return false
527 }
528
529 // ImageSource identifies and decodes an image.
530 type ImageSource interface {
531 DecodeImage() (image.Image, error)
532 Key() string
533 }