69 lines
2 KiB
Go
69 lines
2 KiB
Go
package slideshow
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"image"
|
|
"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(colors []color.Color) {
|
|
if len(colors) == 0 || !config.IsPaletteSet() {
|
|
return
|
|
}
|
|
timestamp := time.Now().UnixMilli()
|
|
var palette string
|
|
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) + "\""
|
|
}
|
|
error := os.WriteFile(config.PaletteFile, []byte(palette), 0775)
|
|
if error != nil {
|
|
loggo.ErrorTimed("encountered an error exporting a color palette", timestamp, error.Error())
|
|
} else {
|
|
loggo.DebugTimed("exported color palette to filesystem", timestamp, "path: "+config.PaletteFile)
|
|
}
|
|
}
|
|
|
|
// extract the given amount of dominant colors of raw image bytes
|
|
func getColorPaletteRaw(data []byte) ([]color.Color, error) {
|
|
var colors []color.Color
|
|
if !config.IsPaletteSet() {
|
|
return colors, nil
|
|
}
|
|
timestamp := time.Now().UnixMilli()
|
|
amount := config.PaletteColors
|
|
img, _, error := image.Decode(bytes.NewReader(data))
|
|
if error != nil {
|
|
loggo.ErrorTimed("encountered an error decoding the provided raw image bytes to an image", timestamp, error.Error())
|
|
return colors, error
|
|
}
|
|
colors, error = color_thief.GetPalette(img, amount, config.PaletteAlgorithm)
|
|
if error != nil {
|
|
loggo.ErrorTimed("encountered an error generating the color palette from raw image bytes", timestamp, "colors: "+strconv.Itoa(amount))
|
|
} else {
|
|
loggo.DebugTimed("generated color palette from raw image bytes", timestamp, "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", uint8(r>>8), uint8(g>>8), uint8(b>>8))
|
|
}
|