avatar.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package avatar
  2. import (
  3. "fmt"
  4. "image"
  5. "image/color/palette"
  6. "math/rand"
  7. "time"
  8. "github.com/issue9/identicon"
  9. )
  10. const AVATAR_SIZE = 290
  11. // RandomImage generates and returns a random avatar image unique to input data
  12. // in custom size (height and width).
  13. func RandomImageSize(size int, data []byte) (image.Image, error) {
  14. randExtent := len(palette.WebSafe) - 32
  15. rand.Seed(time.Now().UnixNano())
  16. colorIndex := rand.Intn(randExtent)
  17. backColorIndex := colorIndex - 1
  18. if backColorIndex < 0 {
  19. backColorIndex = randExtent - 1
  20. }
  21. // Define size, background, and forecolor
  22. imgMaker, err := identicon.New(size,
  23. palette.WebSafe[backColorIndex], palette.WebSafe[colorIndex:colorIndex+32]...)
  24. if err != nil {
  25. return nil, fmt.Errorf("identicon.New: %v", err)
  26. }
  27. return imgMaker.Make(data), nil
  28. }
  29. // RandomImage generates and returns a random avatar image unique to input data
  30. // in default size (height and width).
  31. func RandomImage(data []byte) (image.Image, error) {
  32. return RandomImageSize(AVATAR_SIZE, data)
  33. }