avatar.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, 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. // AvatarSize returns avatar's size
  16. const AvatarSize = 290
  17. // RandomImageSize generates and returns a random avatar image unique to input data
  18. // in custom size (height and width).
  19. func RandomImageSize(size int, data []byte) (image.Image, error) {
  20. randExtent := len(palette.WebSafe) - 32
  21. rand.Seed(time.Now().UnixNano())
  22. colorIndex := rand.Intn(randExtent)
  23. backColorIndex := colorIndex - 1
  24. if backColorIndex < 0 {
  25. backColorIndex = randExtent - 1
  26. }
  27. // Define size, background, and forecolor
  28. imgMaker, err := identicon.New(size,
  29. palette.WebSafe[backColorIndex], palette.WebSafe[colorIndex:colorIndex+32]...)
  30. if err != nil {
  31. return nil, fmt.Errorf("identicon.New: %v", err)
  32. }
  33. return imgMaker.Make(data), nil
  34. }
  35. // RandomImage generates and returns a random avatar image unique to input data
  36. // in default size (height and width).
  37. func RandomImage(data []byte) (image.Image, error) {
  38. return RandomImageSize(AvatarSize, data)
  39. }