avatar.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package avatar
  7. import (
  8. "fmt"
  9. "image"
  10. "image/color/palette"
  11. "math/rand"
  12. "time"
  13. "github.com/issue9/identicon"
  14. )
  15. const AVATAR_SIZE = 290
  16. // RandomImage generates and returns a random avatar image unique to input data
  17. // in custom size (height and width).
  18. func RandomImageSize(size int, data []byte) (image.Image, error) {
  19. randExtent := len(palette.WebSafe) - 32
  20. rand.Seed(time.Now().UnixNano())
  21. colorIndex := rand.Intn(randExtent)
  22. backColorIndex := colorIndex - 1
  23. if backColorIndex < 0 {
  24. backColorIndex = randExtent - 1
  25. }
  26. // Define size, background, and forecolor
  27. imgMaker, err := identicon.New(size,
  28. palette.WebSafe[backColorIndex], palette.WebSafe[colorIndex:colorIndex+32]...)
  29. if err != nil {
  30. return nil, fmt.Errorf("identicon.New: %v", err)
  31. }
  32. return imgMaker.Make(data), nil
  33. }
  34. // RandomImage generates and returns a random avatar image unique to input data
  35. // in default size (height and width).
  36. func RandomImage(data []byte) (image.Image, error) {
  37. return RandomImageSize(AVATAR_SIZE, data)
  38. }