color.go 627 B

12345678910111213141516171819202122232425262728293031323334
  1. package vips
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. var hexColorRegex = regexp.MustCompile("^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
  7. const (
  8. hexColorLongFormat = "%02x%02x%02x"
  9. hexColorShortFormat = "%1x%1x%1x"
  10. )
  11. type Color struct{ R, G, B uint8 }
  12. func ColorFromHex(hexcolor string) (Color, error) {
  13. c := Color{}
  14. if !hexColorRegex.MatchString(hexcolor) {
  15. return c, fmt.Errorf("Invalid hex color: %s", hexcolor)
  16. }
  17. if len(hexcolor) == 3 {
  18. fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
  19. c.R *= 17
  20. c.G *= 17
  21. c.B *= 17
  22. } else {
  23. fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
  24. }
  25. return c, nil
  26. }