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 = "filter"
325 confMain.Key = hashing.HashString(gfilters)
326
327 return i.doWithImageConfig(confMain, func(src image.Image) (image.Image, error) {
328 var filters []gift.Filter
329 for _, f := range gfilters {
330 f = images.UnwrapFilter(f)
331 if specProvider, ok := f.(images.ImageProcessSpecProvider); ok {
332 options := strings.Fields(specProvider.ImageProcessSpec())
333 conf, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format)
334 if err != nil {
335 return nil, err
336 }
337 pFilters, err := i.Proc.FiltersFromConfig(src, conf)
338 if err != nil {
339 return nil, err
340 }
341 filters = append(filters, pFilters...)
342 } else if orientationProvider, ok := f.(images.ImageFilterFromOrientationProvider); ok {
343 var orientation int
344 if meta := i.Meta(); meta != nil {
345 orientation = meta.Orientation
346 }
347 if tf := orientationProvider.AutoOrient(orientation); tf != nil {
348 filters = append(filters, tf)
349 }
350 } else {
351 filters = append(filters, f)
352 }
353 }
354 return i.Proc.Filter(src, filters...)
355 })
356 }
357
358 func (i *imageResource) processActionSpec(action, spec string) (images.ImageResource, error) {
359 options := append([]string{action}, strings.Fields(strings.ToLower(spec))...)
360 ir, err := i.processOptions(options)
361 if err != nil {
362 if sourcePath := i.sourcePath(); sourcePath != "" {
363 err = fmt.Errorf("failed to %s image %q: %w", action, sourcePath, err)
364 }
365 return nil, err
366 }
367 return ir, nil
368 }
369
370 func (i *imageResource) processOptions(options []string) (images.ImageResource, error) {
371 conf, err := images.DecodeImageConfig(options, i.Proc.Cfg, i.Format)
372 if err != nil {
373 return nil, err
374 }
375
376 img, err := i.doWithImageConfig(conf, func(src image.Image) (image.Image, error) {
377 return i.Proc.ApplyFiltersFromConfig(src, conf)
378 })
379 if err != nil {
380 return nil, err
381 }
382
383 if conf.Action == images.ActionFill {
384 if conf.Anchor == images.SmartCropAnchor && img.Width() == 0 || img.Height() == 0 {
385 // See https://github.com/gohugoio/hugo/issues/7955
386 // Smartcrop fails silently in some rare cases.
387 // Fall back to a center fill.
388 conf = conf.Reanchor(gift.CenterAnchor)
389 return i.doWithImageConfig(conf, func(src image.Image) (image.Image, error) {
390 return i.Proc.ApplyFiltersFromConfig(src, conf)
391 })
392 }
393 }
394
395 return img, nil
396 }
397
398 var imageProcSem chan bool
399
400 func init() {
401 imageProcWorkers := 1
402 if n := config.GetNumWorkerMultiplier(); n > 4 {
403 imageProcWorkers = 2
404 }
405 imageProcSem = make(chan bool, imageProcWorkers)
406 }
407
408 func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src image.Image) (image.Image, error)) (images.ImageResource, error) {
409 img, err := i.getSpec().ImageCache.getOrCreate(i, conf, func() (*imageResource, image.Image, error) {
410 imageProcSem <- true
411 defer func() {
412 <-imageProcSem
413 }()
414
415 src, err := i.DecodeImage()
416 if err != nil {
417 return nil, nil, &os.PathError{Op: conf.Action, Path: i.TargetPath(), Err: err}
418 }
419
420 converted, err := f(src)
421 if err != nil {
422 return nil, nil, &os.PathError{Op: conf.Action, Path: i.TargetPath(), Err: err}
423 }
424
425 hasAlpha := !images.IsOpaque(converted)
426 shouldFill := conf.BgColor != nil && hasAlpha
427 shouldFill = shouldFill || (!conf.TargetFormat.SupportsTransparency() && hasAlpha)
428 var bgColor color.Color
429
430 if shouldFill {
431 bgColor = conf.BgColor
432 if bgColor == nil {
433 bgColor = i.Proc.Cfg.Config.BgColor
434 }
435 tmp := image.NewRGBA(converted.Bounds())
436 draw.Draw(tmp, tmp.Bounds(), image.NewUniform(bgColor), image.Point{}, draw.Src)
437 draw.Draw(tmp, tmp.Bounds(), converted, converted.Bounds().Min, draw.Over)
438 converted = tmp
439 }
440
441 if conf.TargetFormat == images.PNG {
442 // Apply the colour palette from the source
443 if paletted, ok := src.(*image.Paletted); ok {
444 palette := paletted.Palette
445 if bgColor != nil && len(palette) < 256 {
446 palette = images.AddColorToPalette(bgColor, palette)
447 } else if bgColor != nil {
448 images.ReplaceColorInPalette(bgColor, palette)
449 }
450 tmp := image.NewPaletted(converted.Bounds(), palette)
451 draw.FloydSteinberg.Draw(tmp, tmp.Bounds(), converted, converted.Bounds().Min)
452 converted = tmp
453 }
454 }
455
456 ci := i.clone(converted)
457 targetPath := i.relTargetPathFromConfig(conf, i.getSpec().Imaging.Cfg.SourceHash)
458 ci.setTargetPath(targetPath)
459 ci.Format = conf.TargetFormat
460 ci.setMediaType(conf.TargetFormat.MediaType())
461
462 return ci, converted, nil
463 })
464 if err != nil {
465 return nil, err
466 }
467 return img, nil
468 }
469
470 // DecodeImage decodes the image source into an Image.
471 // This for internal use only.
472 func (i *imageResource) DecodeImage() (image.Image, error) {
473 f, err := i.ReadSeekCloser()
474 if err != nil {
475 return nil, fmt.Errorf("failed to open image for decode: %w", err)
476 }
477 defer f.Close()
478
479 return i.getSpec().Imaging.Codec.DecodeFormat(i.Format, f)
480 }
481
482 func (i *imageResource) clone(img image.Image) *imageResource {
483 spec := i.baseResource.Clone().(baseResource)
484
485 var image *images.Image
486 if img != nil {
487 image = i.WithImage(img)
488 } else {
489 image = i.WithSpec(spec)
490 }
491
492 ir := &imageResource{
493 Image: image,
494 root: i.root,
495 baseResource: spec,
496 }
497 ir.colorsFn = ir.newColorsFn()
498 return ir
499 }
500
501 func (i *imageResource) getImageMetaCacheTargetPath() string {
502 // Increment to invalidate the meta cache
503 // Last increment: v0.130.0 when change to the new imagemeta library for Exif.
504 const imageMetaVersionNumber = 2
505
506 cfgHash := i.getSpec().Imaging.Cfg.SourceHash
507 df := i.getResourcePaths()
508 p1, _ := paths.FileAndExt(df.File)
509 h := i.hash()
510 idStr := hashing.HashStringHex(h, i.size(), imageMetaVersionNumber, cfgHash)
511 df.File = fmt.Sprintf("%s_%s.json", p1, idStr)
512 return df.TargetPath()
513 }
514
515 func (i *imageResource) relTargetPathFromConfig(conf images.ImageConfig, imagingConfigSourceHash string) internal.ResourcePaths {
516 p1, p2 := paths.FileAndExt(i.getResourcePaths().File)
517 if conf.TargetFormat != i.Format {
518 p2 = conf.TargetFormat.DefaultExtension()
519 }
520
521 // Do not change.
522 const imageHashPrefix = "_hu_"
523
524 huIdx := strings.LastIndex(p1, imageHashPrefix)
525 incomingID := ""
526 if huIdx > -1 {
527 incomingID = p1[huIdx+len(imageHashPrefix):]
528 p1 = p1[:huIdx]
529 }
530
531 hash := hashing.HashStringHex(incomingID, i.hash(), conf.Key, imagingConfigSourceHash)
532 rp := i.getResourcePaths()
533 rp.File = fmt.Sprintf("%s%s%s%s", p1, imageHashPrefix, hash, p2)
534
535 return rp
536 }