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 filters = append(filters, gift.Rotate(float32(conf.Rotate), color.Transparent, gift.NearestNeighborInterpolation))
193 }
194
195 switch conf.Action {
196 case "resize":
197 filters = append(filters, gift.Resize(conf.Width, conf.Height, conf.Filter))
198 case "crop":
199 if conf.Anchor == SmartCropAnchor {
200 bounds, err := p.smartCrop(src, conf.Width, conf.Height, conf.Filter)
201 if err != nil {
202 return nil, err
203 }
204
205 // First crop using the bounds returned by smartCrop.
206 filters = append(filters, gift.Crop(bounds))
207 // Then center crop the image to get an image the desired size without resizing.
208 filters = append(filters, gift.CropToSize(conf.Width, conf.Height, gift.CenterAnchor))
209
210 } else {
211 filters = append(filters, gift.CropToSize(conf.Width, conf.Height, conf.Anchor))
212 }
213 case "fill":
214 if conf.Anchor == SmartCropAnchor {
215 bounds, err := p.smartCrop(src, conf.Width, conf.Height, conf.Filter)
216 if err != nil {
217 return nil, err
218 }
219
220 // First crop it, then resize it.
221 filters = append(filters, gift.Crop(bounds))
222 filters = append(filters, gift.Resize(conf.Width, conf.Height, conf.Filter))
223
224 } else {
225 filters = append(filters, gift.ResizeToFill(conf.Width, conf.Height, conf.Filter, conf.Anchor))
226 }
227 case "fit":
228 filters = append(filters, gift.ResizeToFit(conf.Width, conf.Height, conf.Filter))
229 default:
230
231 }
232 return filters, nil
233 }
234
235 func (p *ImageProcessor) ApplyFiltersFromConfig(src image.Image, conf ImageConfig) (image.Image, error) {
236 filters, err := p.FiltersFromConfig(src, conf)
237 if err != nil {
238 return nil, err
239 }
240
241 if len(filters) == 0 {
242 return p.resolveSrc(src, conf.TargetFormat), nil
243 }
244
245 img, err := p.doFilter(src, conf.TargetFormat, filters...)
246 if err != nil {
247 return nil, err
248 }
249
250 return img, nil
251 }
252
253 func (p *ImageProcessor) Filter(src image.Image, filters ...gift.Filter) (image.Image, error) {
254 return p.doFilter(src, 0, filters...)
255 }
256
257 func (p *ImageProcessor) resolveSrc(src image.Image, targetFormat Format) image.Image {
258 if animatedImage, ok := src.(himage.AnimatedImage); ok {
259 frames := animatedImage.GetFrames()
260 // If e.g. converting an animated GIF to JPEG, we only want the first frame.
261 // Preserve the AnimatedImage wrapper for color properties only when there is
262 // no actual animation to preserve. Multi-frame animated sources must still be
263 // collapsed unless the target format supports animation output.
264 shouldExtractFirstFrame := len(frames) < 2 || !targetFormat.SupportsAnimation()
265 colorPropsNeedPreserving := himage.HasColorProperties(src) && len(frames) < 2
266 if shouldExtractFirstFrame && !colorPropsNeedPreserving {
267 src = frames[0]
268 }
269 }
270 return src
271 }
272
273 func (p *ImageProcessor) doFilter(src image.Image, targetFormat Format, filters ...gift.Filter) (image.Image, error) {
274 filter := gift.New(filters...)
275
276 if anim, ok := src.(himage.AnimatedImage); ok {
277 frames := anim.GetFrames()
278 // Check if we should extract first frame or preserve AnimatedImage wrapper.
279 // Preserve AnimatedImage if color properties need to be maintained.
280 shouldExtractFirstFrame := len(frames) < 2 || !targetFormat.SupportsAnimation()
281 colorPropsNeedPreserving := himage.HasColorProperties(src) && len(frames) < 2
282 if shouldExtractFirstFrame && !colorPropsNeedPreserving {
283 src = frames[0]
284 } else {
285 var bounds image.Rectangle
286 firstFrame := frames[0]
287 // Preserve bit depth for HDR images.
288 var tmp draw.Image
289 switch firstFrame.(type) {
290 case *image.RGBA64, *image.NRGBA64:
291 tmp = image.NewNRGBA64(firstFrame.Bounds())
292 default:
293 tmp = image.NewNRGBA(firstFrame.Bounds())
294 }
295 for i, frame := range frames {
296 gift.New().DrawAt(tmp, frame, frame.Bounds().Min, gift.OverOperator)
297 bounds = filter.Bounds(tmp.Bounds())
298 var dst draw.Image
299 switch f := frame.(type) {
300 case *image.Paletted:
301 // Gif.
302 dst = image.NewPaletted(bounds, f.Palette)
303 case *image.RGBA64:
304 dst = image.NewRGBA64(bounds)
305 case *image.NRGBA64:
306 dst = image.NewNRGBA64(bounds)
307 default:
308 dst = image.NewNRGBA(bounds)
309 }
310 filter.Draw(dst, tmp)
311 frames[i] = dst
312 }
313 anim.SetWidthHeight(bounds.Dx(), bounds.Dy())
314 anim.SetFrames(frames)
315
316 return anim, nil
317 }
318
319 }
320
321 bounds := filter.Bounds(src.Bounds())
322
323 var dst draw.Image
324 switch src.(type) {
325 case *image.RGBA:
326 dst = image.NewRGBA(bounds)
327 case *image.NRGBA:
328 dst = image.NewNRGBA(bounds)
329 case *image.Gray:
330 dst = image.NewGray(bounds)
331 case *image.RGBA64:
332 dst = image.NewRGBA64(bounds)
333 case *image.NRGBA64:
334 dst = image.NewNRGBA64(bounds)
335 case *image.Gray16:
336 dst = image.NewGray16(bounds)
337 default:
338 dst = image.NewNRGBA(bounds)
339 }
340 filter.Draw(dst, src)
341
342 return dst, nil
343 }
344
345 func newImageConfig() ImageConfig {
346 return ImageConfig{
347 Anchor: -1, // The real values start at 0.
348 }
349 }
350
351 type Spec interface {
352 // Loads the image source.
353 ReadSeekCloser() (hugio.ReadSeekCloser, error)
354 }
355
356 // Format is an image file format.
357 type Format int
358
359 const (
360 JPEG Format = iota + 1
361 PNG
362 GIF
363 TIFF
364 BMP
365 WEBP
366 AVIF
367
368 // Below: We have no encoder/decoder for these, but we can provide metadata support for them (including width/height).
369 HEIF
370 HEIC
371 )
372
373 // Whether to use imagemeta to decode image config (width/height ).
374 func (f Format) UseImageMetaConfigDecoder() bool {
375 return f == WEBP || f == AVIF || f == HEIF || f == HEIC
376 }
377
378 func (f Format) ToImageMetaImageFormatFormat() imagemeta.ImageFormat {
379 switch f {
380 case JPEG:
381 return imagemeta.JPEG
382 case PNG:
383 return imagemeta.PNG
384 case TIFF:
385 return imagemeta.TIFF
386 case WEBP:
387 return imagemeta.WebP
388 case AVIF:
389 return imagemeta.AVIF
390 case HEIF:
391 return imagemeta.HEIF
392 case HEIC:
393 return imagemeta.HEIF
394 default:
395 return -1
396 }
397 }
398
399 // SupportsTransparency reports whether it supports transparency in any form.
400 func (f Format) SupportsTransparency() bool {
401 return f != JPEG
402 }
403
404 // SupportsAnimation reports whether the format supports animation.
405 // AVIF supports animation in the spec, but Hugo's AVIF encoder is single-frame
406 // only — including AVIF here would make the pipeline preserve frames just to
407 // drop them at encode time.
408 func (f Format) SupportsAnimation() bool {
409 return f == GIF || f == WEBP
410 }
411
412 // DefaultExtension returns the default file extension of this format, starting with a dot.
413 // For example: .jpg for JPEG
414 func (f Format) DefaultExtension() string {
415 return f.MediaType().FirstSuffix.FullSuffix
416 }
417
418 // MediaType returns the media type of this image, e.g. image/jpeg for JPEG
419 func (f Format) MediaType() media.Type {
420 switch f {
421 case JPEG:
422 return media.Builtin.JPEGType
423 case PNG:
424 return media.Builtin.PNGType
425 case GIF:
426 return media.Builtin.GIFType
427 case TIFF:
428 return media.Builtin.TIFFType
429 case BMP:
430 return media.Builtin.BMPType
431 case WEBP:
432 return media.Builtin.WEBPType
433 case AVIF:
434 return media.Builtin.AVIFType
435 case HEIF:
436 return media.Builtin.HEIFType
437 case HEIC:
438 return media.Builtin.HEICType
439 default:
440 panic(fmt.Sprintf("%d is not a valid image format", f))
441 }
442 }
443
444 func (f Format) String() string {
445 switch f {
446 case JPEG:
447 return "JPEG"
448 case PNG:
449 return "PNG"
450 case GIF:
451 return "GIF"
452 case TIFF:
453 return "TIFF"
454 case BMP:
455 return "BMP"
456 case WEBP:
457 return "WEBP"
458 case AVIF:
459 return "AVIF"
460 case HEIF:
461 return "HEIF"
462 case HEIC:
463 return "HEIC"
464 default:
465 return "Unknown"
466 }
467 }
468
469 type imageConfig struct {
470 config image.Config
471 configInit sync.Once
472 configLoaded bool
473 }
474
475 func imageConfigFromImage(img image.Image) image.Config {
476 if cp, ok := img.(himage.ImageConfigProvider); ok {
477 return cp.GetImageConfig()
478 }
479 b := img.Bounds()
480 return image.Config{Width: b.Max.X, Height: b.Max.Y}
481 }
482
483 // UnwrapFilter unwraps the given filter if it is a filter wrapper.
484 func UnwrapFilter(in gift.Filter) gift.Filter {
485 if f, ok := in.(filter); ok {
486 return f.Filter
487 }
488 return in
489 }
490
491 // ToFilters converts the given input to a slice of gift.Filter.
492 func ToFilters(in any) []gift.Filter {
493 switch v := in.(type) {
494 case []gift.Filter:
495 return v
496 case []filter:
497 vv := make([]gift.Filter, len(v))
498 for i, f := range v {
499 vv[i] = f
500 }
501 return vv
502 case gift.Filter:
503 return []gift.Filter{v}
504 default:
505 panic(fmt.Sprintf("%T is not an image filter", in))
506 }
507 }
508
509 // IsOpaque returns false if the image has alpha channel and there is at least 1
510 // pixel that is not (fully) opaque.
511 func IsOpaque(img image.Image) bool {
512 if oim, ok := img.(interface {
513 Opaque() bool
514 }); ok {
515 return oim.Opaque()
516 }
517
518 return false
519 }
520
521 // ImageSource identifies and decodes an image.
522 type ImageSource interface {
523 DecodeImage() (image.Image, error)
524 Key() string
525 }