utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package gocaptcha
  2. import (
  3. "image/color"
  4. "math/rand"
  5. )
  6. // RandDeepColor 随机生成深色系.
  7. func RandDeepColor() color.RGBA {
  8. // 限制 RGB 最大值为 150 (深色系),最小值为 50
  9. maxValue := 150
  10. minValue := 50
  11. r := uint8(rand.Intn(maxValue-minValue+1) + minValue)
  12. g := uint8(rand.Intn(maxValue-minValue+1) + minValue)
  13. b := uint8(rand.Intn(maxValue-minValue+1) + minValue)
  14. // Alpha 通道设置为完全不透明
  15. a := uint8(rand.Intn(256))
  16. return color.RGBA{R: r, G: g, B: b, A: a}
  17. }
  18. // RandLightColor 随机生成浅色.
  19. //func RandLightColor() color.RGBA {
  20. // // 为每个颜色分量生成一个128到255之间的随机数
  21. // red := rand.Intn(128) + 128
  22. // green := rand.Intn(128) + 128
  23. // blue := rand.Intn(128) + 128
  24. // // Alpha 通道设置为完全不透明
  25. // a := uint8(rand.Intn(256))
  26. //
  27. // return color.RGBA{R: uint8(red), G: uint8(green), B: uint8(blue), A: a}
  28. //}
  29. // RandColor 生成随机颜色.
  30. func RandColor() color.RGBA {
  31. red := rand.Intn(255)
  32. green := rand.Intn(255)
  33. var blue int
  34. // Calculate blue value based on the sum of red and green
  35. sum := red + green
  36. if sum > 400 {
  37. blue = 0
  38. } else {
  39. blueTemp := 400 - sum
  40. blue = max(0, min(255, blueTemp))
  41. }
  42. return color.RGBA{R: uint8(red), G: uint8(green), B: uint8(blue), A: 255}
  43. }
  44. // RandText 生成随机字体.
  45. //func RandText(num int) string {
  46. // textNum := len(TextCharacters)
  47. // text := make([]rune, num)
  48. // for i := 0; i < num; i++ {
  49. // text[i] = TextCharacters[rand.Intn(textNum)]
  50. // }
  51. // return string(text)
  52. //}
  53. // ColorToRGB 颜色代码转换为RGB
  54. // input int
  55. // output int red, green, blue.
  56. func ColorToRGB(colorVal int) color.RGBA {
  57. red := colorVal >> 16
  58. green := (colorVal & 0x00FF00) >> 8
  59. blue := colorVal & 0x0000FF
  60. return color.RGBA{
  61. R: uint8(red),
  62. G: uint8(green),
  63. B: uint8(blue),
  64. A: uint8(255),
  65. }
  66. }
  67. // 整数绝对值函数
  68. func abs[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64](a T) T {
  69. var zero T
  70. if a < zero {
  71. return -a
  72. }
  73. return a
  74. }
  75. func max(x,y int) int{
  76. if x<y{
  77. return y
  78. }
  79. return x
  80. }
  81. func min(x , y int) int{
  82. if x>y{
  83. return y
  84. }
  85. return x
  86. }