resources/images: Add $image.Colors

Which returns the most dominant colors of an image using a simple histogram method.

Fixes #10307
This commit is contained in:
Bjørn Erik Pedersen
2022-09-21 16:24:54 +02:00
parent 08f0984f91
commit a4028112e3
10 changed files with 90 additions and 0 deletions

View File

@@ -30,6 +30,8 @@ import (
"strings"
"sync"
color_extractor "github.com/marekm4/color-extractor"
"github.com/gohugoio/hugo/common/paths"
"github.com/disintegration/gift"
@@ -64,6 +66,9 @@ type imageResource struct {
metaInitErr error
meta *imageMeta
dominantColorInit sync.Once
dominantColors []string
baseResource
}
@@ -135,6 +140,24 @@ func (i *imageResource) getExif() *exif.ExifInfo {
return i.meta.Exif
}
// Colors returns a slice of the most dominant colors in an image
// using a simple histogram method.
func (i *imageResource) Colors() ([]string, error) {
var err error
i.dominantColorInit.Do(func() {
var img image.Image
img, err = i.DecodeImage()
if err != nil {
return
}
colors := color_extractor.ExtractColors(img)
for _, c := range colors {
i.dominantColors = append(i.dominantColors, images.ColorToHexString(c))
}
})
return i.dominantColors, nil
}
// Clone is for internal use.
func (i *imageResource) Clone() resource.Resource {
gr := i.baseResource.Clone().(baseResource)