slideshow/internal/slideshow/palette.go

69 lines
1.6 KiB
Go

package slideshow
import (
"fmt"
"image/color"
"os"
"strconv"
"time"
"git.velvettear.de/velvettear/loggo"
"git.velvettear.de/velvettear/slideshow/internal/config"
color_thief "github.com/kennykarnama/color-thief"
)
// write the base16 color palette to a file
func exportPalette() error {
if !config.IsPaletteSet() {
return nil
}
var palette string
colors, error := getColorPalette(image, 16)
if error != nil {
return error
}
for index, color := range colors {
if index > 0 {
palette += "\n"
}
tmp := strconv.Itoa(index)
if len(tmp) < 2 {
tmp = "0" + tmp
}
tmp = "SLIDESHOW_COLOR" + tmp
palette += tmp + "=\"" + rgbToHex(color) + "\""
}
return os.WriteFile(config.Palette, []byte(palette), 0775)
}
// get the base16 color palette from an image
func GetBase16Colors(image string) (string, error) {
var base16 string
colors, error := getColorPalette(image, 16)
if error != nil {
return base16, error
}
for index, color := range colors {
if index > 0 {
base16 += "\n"
}
base16 += rgbToHex(color)
}
return base16, nil
}
// extract the given amount of dominant colors an image
func getColorPalette(image string, amount int) ([]color.Color, error) {
timestamp := time.Now().UnixMilli()
colors, error := color_thief.GetPaletteFromFile(image, amount, 0)
if error == nil {
loggo.DebugTimed("generated color palette from image", timestamp, "image: "+image, "colors: "+strconv.Itoa(amount))
}
return colors, error
}
// parse rgb color values to hex
func rgbToHex(color color.Color) string {
r, g, b, _ := color.RGBA()
return fmt.Sprintf("#%02x%02x%02x", r, g, b)
}