Debian Codegraph @

resources/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 resources
15
16 import (
17 "encoding/json"
18 "fmt"
19 "image"
20 "image/color"
21 "image/draw"
22 "io"
23 "os"
24 "strings"
25 "sync"
26
27 color_extractor "github.com/marekm4/color-extractor"
28
29 "github.com/gohugoio/hugo/cache/filecache"
30 "github.com/gohugoio/hugo/common/hashing"
31 "github.com/gohugoio/hugo/common/hugo"
32 "github.com/gohugoio/hugo/common/paths"
33 "github.com/gohugoio/hugo/config"
34
35 "github.com/gohugoio/gift"
36
37 "github.com/gohugoio/hugo/resources/images/meta"
38 "github.com/gohugoio/hugo/resources/internal"
39
40 "github.com/gohugoio/hugo/resources/resource"
41
42 "github.com/gohugoio/hugo/resources/images"
43 )
44
45 var (
46 _ images.ImageResource = (*imageResource)(nil)
47 _ resource.Source = (*imageResource)(nil)
48 _ resource.Cloner = (*imageResource)(nil)
49 _ resource.NameNormalizedProvider = (*imageResource)(nil)
50 _ targetPathProvider = (*imageResource)(nil)
51 )
52
53 // imageResource represents an image resource.
54 type imageResource struct {
55 *images.Image
56
57 // When a image is processed in a chain, this holds the reference to the
58 // original (first).
59 root *imageResource
60
61 // These 2 are only set for the root imageResource.
62 exifInfoFn func() (*meta.ExifInfo, error)
63 metaInfoFn func() (*meta.MetaInfo, error)
64
65 colorsFn func() ([]images.Color, error)
66
67 baseResource
68 }
69
70 func newImageResource(img *images.Image, base baseResource) *imageResource {
71 ir := &imageResource{
72 Image: img,
73 baseResource: base,
74 }
75 ir.root = ir
76 ir.exifInfoFn = ir.newExifInfoFn()
77 ir.metaInfoFn = ir.newMetaInfoFn()
78 ir.colorsFn = ir.newColorsFn()
79 return ir
80 }
81
82 func (i *imageResource) newExifInfoFn() func() (*meta.ExifInfo, error) {
83 return sync.OnceValues(func() (*meta.ExifInfo, error) {
84 hugo.Deprecate("Image.Exif", "Use Image.Meta, see https://gohugo.io/content-management/image-processing/#meta", "v0.155.0")
85 mf := i.Format.ToImageMetaImageFormatFormat()
86 if mf == -1 {
87 return nil, nil
88 }
89
90 var result *meta.ExifInfo
91 key := i.getImageMetaCacheTargetPath()
92
93 read := func(info filecache.ItemInfo, r io.ReadSeeker) error {
94 data, err := io.ReadAll(r)
95 if err != nil {
96 return err
97 }
98 return json.Unmarshal(data, &result)
99 }
100
101 create := func(info filecache.ItemInfo, w io.WriteCloser) (err error) {
102 defer w.Close()
103 f, err := i.ReadSeekCloser()
104 if err != nil {
105 return err
106 }
107 defer f.Close()
108
109 filename := InternalResourceSourcePathBestEffort(i)
110 result, err = i.getSpec().Imaging.DecodeExif(filename, mf, f)
111 if err != nil {
112 i.getSpec().Logger.Warnf("Unable to decode Exif metadata from image: %s", i.Key())
113 return nil
114 }
115
116 enc := json.NewEncoder(w)
117 return enc.Encode(result)
118 }
119
120 _, err := i.getSpec().ImageCache.fcache.ReadOrCreate(key, read, create)
121 return result, err
122 })
123 }
124
125 func (i *imageResource) newMetaInfoFn() func() (*meta.MetaInfo, error) {
126 return sync.OnceValues(func() (*meta.MetaInfo, error) {
127 mf := i.Format.ToImageMetaImageFormatFormat()
128 if mf == -1 {
129 return nil, nil
130 }
131
132 var result *meta.MetaInfo
133 key := i.getImageMetaInfoCacheTargetPath()
134
135 read := func(info filecache.ItemInfo, r io.ReadSeeker) error {
136 data, err := io.ReadAll(r)
137 if err != nil {
138 return err
139 }
140 return json.Unmarshal(data, &result)
141 }
142
143 create := func(info filecache.ItemInfo, w io.WriteCloser) (err error) {
144 defer w.Close()
145 f, err := i.ReadSeekCloser()
146 if err != nil {
147 return err
148 }
149 defer f.Close()
150
151 filename := InternalResourceSourcePathBestEffort(i)
152 result, err = i.getSpec().Imaging.DecodeMeta(filename, mf, f)
153 if err != nil {
154 i.getSpec().Logger.Warnf("Unable to decode metadata from image: %s", i.Key())
155 return nil
156 }
157
158 enc := json.NewEncoder(w)
159 return enc.Encode(result)
160 }
161
162 _, err := i.getSpec().ImageCache.fcache.ReadOrCreate(key, read, create)
163 return result, err
164 })
165 }
166
167 func (i *imageResource) newColorsFn() func() ([]images.Color, error) {
168 return sync.OnceValues(func() ([]images.Color, error) {
169 img, err := i.DecodeImage()
170 if err != nil {
171 return nil, err
172 }
173 colors := color_extractor.ExtractColors(img)
174 result := make([]images.Color, len(colors))
175 for j, c := range colors {
176 result[j] = images.ColorGoToColor(c)
177 }
178 return result, nil
179 })
180 }
181
182 func (i *imageResource) Exif() *meta.ExifInfo {
183 x, err := i.root.exifInfoFn()
184 if err != nil {
185 panic(fmt.Sprintf("exif init failed: %s", err))
186 }
187 return x
188 }
189
190 func (i *imageResource) Meta() *meta.MetaInfo {
191 m, err := i.root.metaInfoFn()
192 if err != nil {
193 panic(fmt.Sprintf("meta init failed: %s", err))
194 }
195 return m
196 }
197
198 func (i *imageResource) getImageMetaInfoCacheTargetPath() string {
199 // Increment to invalidate the meta cache
200 const imageMetaInfoVersionNumber = 1
201
202 cfgHash := i.getSpec().Imaging.Cfg.SourceHash
203 df := i.getResourcePaths()
204 p1, _ := paths.FileAndExt(df.File)
205 h := i.hash()
206 idStr := hashing.HashStringHex(h, i.size(), imageMetaInfoVersionNumber, cfgHash)
207 df.File = fmt.Sprintf("%s_%s_meta.json", p1, idStr)
208 return df.TargetPath()
209 }
210
211 // Colors returns a slice of the most dominant colors in an image
212 // using a simple histogram method.
213 func (i *imageResource) Colors() ([]images.Color, error) {
214 return i.colorsFn()
215 }
216
217 func (i *imageResource) targetPath() string {
218 return i.TargetPath()
219 }
220
221 // Clone is for internal use.
222 func (i *imageResource) Clone() resource.Resource {
223 gr := i.baseResource.Clone().(baseResource)
224 ir := &imageResource{
225 root: i.root,
226 Image: i.WithSpec(gr),
227 baseResource: gr,
228 }
229 ir.colorsFn = ir.newColorsFn()
230 return ir
231 }
232
233 func (i *imageResource) cloneTo(targetPath string) resource.Resource {
234 gr := i.baseResource.cloneTo(targetPath).(baseResource)
235 ir := &imageResource{
236 root: i.root,
237 Image: i.WithSpec(gr),
238 baseResource: gr,
239 }
240 ir.colorsFn = ir.newColorsFn()
241 return ir
242 }
243
244 func (i *imageResource) cloneWithUpdates(u *transformationUpdate) (baseResource, error) {
245 base, err := i.baseResource.cloneWithUpdates(u)
246 if err != nil {
247 return nil, err
248 }
249
250 var img *images.Image
251
252 if u.isContentChanged() {
253 img = i.WithSpec(base)
254 } else {
255 img = i.Image
256 }
257
258 ir := &imageResource{
259 root: i.root,
260 Image: img,
261 baseResource: base,
262 }
263 ir.colorsFn = ir.newColorsFn()
264 return ir, nil
265 }
266
267 // Process processes the image with the given spec.
268 // The spec can contain an optional action, one of "resize", "crop", "fit" or "fill".
269 // This makes this method a more flexible version that covers all of Resize, Crop, Fit and Fill,
270 // but it also supports e.g. format conversions without any resize action.
271 func (i *imageResource) Process(spec string) (images.ImageResource, error) {
272 return i.processActionSpec("", spec)
273 }
274
275 // Resize resizes the image to the specified width and height using the specified resampling
276 // filter and returns the transformed image. If one of width or height is 0, the image aspect
277 // ratio is preserved.
278 func (i *imageResource) Resize(spec string) (images.ImageResource, error) {
279 return i.processActionSpec(images.ActionResize, spec)
280 }
281
282 // Crop the image to the specified dimensions without resizing using the given anchor point.
283 // Space delimited config, e.g. `200x300 TopLeft`.
284 func (i *imageResource) Crop(spec string) (images.ImageResource, error) {
285 return i.processActionSpec(images.ActionCrop, spec)
286 }
287
288 // Fit scales down the image using the specified resample filter to fit the specified
289 // maximum width and height.
290 func (i *imageResource) Fit(spec string) (images.ImageResource, error) {
291 return i.processActionSpec(images.ActionFit, spec)
292 }
293
294 // Fill scales the image to the smallest possible size that will cover the specified dimensions,
295 // crops the resized image to the specified dimensions using the given anchor point.
296 // Space delimited config, e.g. `200x300 TopLeft`.
297 func (i *imageResource) Fill(spec string) (images.ImageResource, error) {
298 return i.processActionSpec(images.ActionFill, spec)
299 }
300
301 func (i *imageResource) Filter(filters ...any) (images.ImageResource, error) {
302 var confMain images.ImageConfig
303
304 var gfilters []gift.Filter
305
306 for _, f := range filters {
307 gfilters = append(gfilters, images.ToFilters(f)...)
308 }
309
310 var options []string
311
312 for _, f := range gfilters {
313 f = images.UnwrapFilter(f)
314 if specProvider, ok := f.(images.ImageProcessSpecProvider); ok {
315 options = append(options, strings.Fields(specProvider.ImageProcessSpec())...)
316 }
317 }
318
319 confMain, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format)
320 if err != nil {
321 return nil, err
322 }
323
324 confMain.Action = images.ActionFilter
325 opts := []any{gfilters}
326 if images.MainImageVersionNumber > 0 {
327 opts = append(opts, images.MainImageVersionNumber)
328 }
329 if v := images.FormatVersionNumbers[confMain.TargetFormat]; v > 0 {
330 opts = append(opts, v)
331 }
332 confMain.Key = hashing.HashString(opts...)
333
334 // Geometric filters cannot introduce colors outside the source palette.
335 for _, f := range gfilters {
336 switch images.UnwrapFilter(f).(type) {
337 case images.ImageProcessSpecProvider, images.ImageFilterFromOrientationProvider:
338 default:
339 confMain.PreserveSourcePalette = false
340 }
341 }
342
343 return i.doWithImageConfig(confMain, func(src image.Image) (image.Image, error) {
344 var filters []gift.Filter
345 for _, f := range gfilters {
346 f = images.UnwrapFilter(f)
347 if specProvider, ok := f.(images.ImageProcessSpecProvider); ok {
348 options := strings.Fields(specProvider.ImageProcessSpec())
349 conf, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format)
350 if err != nil {
351 return nil, err
352 }
353 pFilters, err := i.Proc.FiltersFromConfig(src, conf)
354 if err != nil {
355 return nil, err
356 }
357 filters = append(filters, pFilters...)
358 } else if orientationProvider, ok := f.(images.ImageFilterFromOrientationProvider); ok {
359 var orientation int
360 if meta := i.Meta(); meta != nil {
361 orientation = meta.Orientation
362 }
363 if tf := orientationProvider.AutoOrient(orientation); tf != nil {
364 filters = append(filters, tf)
365 }
366 } else {
367 filters = append(filters, f)
368 }
369 }
370 return i.Proc.Filter(src, filters...)
371 })
372 }
373
374 func (i *imageResource) processActionSpec(action, spec string) (images.ImageResource, error) {
375 options := append([]string{action}, strings.Fields(strings.ToLower(spec))...)
376 ir, err := i.processOptions(options)
377 if err != nil {
378 if sourcePath := i.sourcePath(); sourcePath != "" {
379 err = fmt.Errorf("failed to %s image %q: %w", action, sourcePath, err)
380 }
381 return nil, err
382 }
383 return ir, nil
384 }
385
386 func (i *imageResource) processOptions(options []string) (images.ImageResource, error) {
387 conf, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format)
388 if err != nil {
389 return nil, err
390 }
391
392 img, err := i.doWithImageConfig(conf, func(src image.Image) (image.Image, error) {
393 return i.Proc.ApplyFiltersFromConfig(src, conf)
394 })
395 if err != nil {
396 return nil, err
397 }
398
399 if conf.Action == images.ActionFill {
400 if conf.Anchor == images.SmartCropAnchor && img.Width() == 0 || img.Height() == 0 {
401 // See https://github.com/gohugoio/hugo/issues/7955
402 // Smartcrop fails silently in some rare cases.
403 // Fall back to a center fill.
404 conf = conf.Reanchor(gift.CenterAnchor)
405 return i.doWithImageConfig(conf, func(src image.Image) (image.Image, error) {
406 return i.Proc.ApplyFiltersFromConfig(src, conf)
407 })
408 }
409 }
410
411 return img, nil
412 }
413
414 var imageProcSem chan bool
415
416 func init() {
417 imageProcWorkers := 1
418 if n := config.GetNumWorkerMultiplier(); n > 4 {
419 imageProcWorkers = 2
420 }
421 imageProcSem = make(chan bool, imageProcWorkers)
422 }
423
424 func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src image.Image) (image.Image, error)) (images.ImageResource, error) {
425 img, err := i.getSpec().ImageCache.getOrCreate(i, conf, func() (*imageResource, image.Image, error) {
426 imageProcSem <- true
427 defer func() {
428 <-imageProcSem
429 }()
430
431 src, err := i.DecodeImage()
432 if err != nil {
433 return nil, nil, &os.PathError{Op: conf.Action, Path: i.TargetPath(), Err: err}
434 }
435
436 converted, err := f(src)
437 if err != nil {
438 return nil, nil, &os.PathError{Op: conf.Action, Path: i.TargetPath(), Err: err}
439 }
440
441 hasAlpha := !images.IsOpaque(converted)
442 shouldFill := conf.BgColor != nil && hasAlpha
443 shouldFill = shouldFill || (!conf.TargetFormat.SupportsTransparency() && hasAlpha)
444 var bgColor color.Color
445
446 if shouldFill {
447 bgColor = conf.BgColor
448 if bgColor == nil {
449 bgColor = i.Proc.Cfg.Config.BgColor
450 }
451 tmp := image.NewRGBA(converted.Bounds())
452 draw.Draw(tmp, tmp.Bounds(), image.NewUniform(bgColor), image.Point{}, draw.Src)
453 draw.Draw(tmp, tmp.Bounds(), converted, converted.Bounds().Min, draw.Over)
454 converted = tmp
455 }
456
457 if conf.TargetFormat == images.PNG && conf.PreserveSourcePalette {
458 // Apply the colour palette from the source
459 if paletted, ok := src.(*image.Paletted); ok {
460 palette := paletted.Palette
461 if bgColor != nil && len(palette) < 256 {
462 palette = images.AddColorToPalette(bgColor, palette)
463 } else if bgColor != nil {
464 images.ReplaceColorInPalette(bgColor, palette)
465 }
466 tmp := image.NewPaletted(converted.Bounds(), palette)
467 draw.FloydSteinberg.Draw(tmp, tmp.Bounds(), converted, converted.Bounds().Min)
468 converted = tmp
469 }
470 }
471
472 ci := i.clone(converted)
473 targetPath := i.relTargetPathFromConfig(conf, i.getSpec().Imaging.Cfg.SourceHash)
474 ci.setTargetPath(targetPath)
475 ci.Format = conf.TargetFormat
476 ci.setMediaType(conf.TargetFormat.MediaType())
477
478 return ci, converted, nil
479 })
480 if err != nil {
481 return nil, err
482 }
483 return img, nil
484 }
485
486 // DecodeImage decodes the image source into an Image.
487 // This for internal use only.
488 func (i *imageResource) DecodeImage() (image.Image, error) {
489 f, err := i.ReadSeekCloser()
490 if err != nil {
491 return nil, fmt.Errorf("failed to open image for decode: %w", err)
492 }
493 defer f.Close()
494
495 return i.getSpec().Imaging.Codec.DecodeFormat(i.Format, f)
496 }
497
498 func (i *imageResource) clone(img image.Image) *imageResource {
499 spec := i.baseResource.Clone().(baseResource)
500
501 var image *images.Image
502 if img != nil {
503 image = i.WithImage(img)
504 } else {
505 image = i.WithSpec(spec)
506 }
507
508 ir := &imageResource{
509 Image: image,
510 root: i.root,
511 baseResource: spec,
512 }
513 ir.colorsFn = ir.newColorsFn()
514 return ir
515 }
516
517 func (i *imageResource) getImageMetaCacheTargetPath() string {
518 // Increment to invalidate the meta cache
519 // Last increment: v0.130.0 when change to the new imagemeta library for Exif.
520 const imageMetaVersionNumber = 2
521
522 cfgHash := i.getSpec().Imaging.Cfg.SourceHash
523 df := i.getResourcePaths()
524 p1, _ := paths.FileAndExt(df.File)
525 h := i.hash()
526 idStr := hashing.HashStringHex(h, i.size(), imageMetaVersionNumber, cfgHash)
527 df.File = fmt.Sprintf("%s_%s.json", p1, idStr)
528 return df.TargetPath()
529 }
530
531 func (i *imageResource) relTargetPathFromConfig(conf images.ImageConfig, imagingConfigSourceHash string) internal.ResourcePaths {
532 p1, p2 := paths.FileAndExt(i.getResourcePaths().File)
533 if conf.TargetFormat != i.Format {
534 p2 = conf.TargetFormat.DefaultExtension()
535 }
536
537 // Do not change.
538 const imageHashPrefix = "_hu_"
539
540 huIdx := strings.LastIndex(p1, imageHashPrefix)
541 incomingID := ""
542 if huIdx > -1 {
543 incomingID = p1[huIdx+len(imageHashPrefix):]
544 p1 = p1[:huIdx]
545 }
546
547 hash := hashing.HashStringHex(incomingID, i.hash(), conf.Key, imagingConfigSourceHash)
548 rp := i.getResourcePaths()
549 rp.File = fmt.Sprintf("%s%s%s%s", p1, imageHashPrefix, hash, p2)
550
551 return rp
552 }