package internal import ( "bytes" "fmt" "image" "image/color" "strconv" "time" "git.velvettear.de/velvettear/loggo" "git.velvettear.de/velvettear/slideshow-api/internal/config" color_thief "github.com/kennykarnama/color-thief" ) // extract the given amount of dominant colors of raw image bytes func GetColorPalette(data []byte) (string, error) { var palette string 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 palette, 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)) return palette, error } else { loggo.DebugTimed("generated color palette from raw image bytes", timestamp, "colors: "+strconv.Itoa(amount)) } 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 palette, nil } // extract the given amount of dominant colors of an image func getColorPalette(image string) ([]color.Color, error) { var colors []color.Color timestamp := time.Now().UnixMilli() amount := config.PaletteColors colors, error := color_thief.GetPaletteFromFile(image, amount, config.PaletteAlgorithm) if error != nil { loggo.ErrorTimed("encountered an error generating the color palette from image", timestamp, "image: "+image, "colors: "+strconv.Itoa(amount)) } else { 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", uint8(r>>8), uint8(g>>8), uint8(b>>8)) }