color.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package image
  2. import (
  3. "fmt"
  4. "github.com/gographics/gmagick"
  5. "icloudapp.cn/tools/util"
  6. "strconv"
  7. "strings"
  8. )
  9. type Color struct {
  10. Red uint32
  11. Green uint32
  12. Blue uint32
  13. Alpha uint32
  14. R uint8
  15. G uint8
  16. B uint8
  17. A uint8
  18. }
  19. func NewColor(color string) *Color {
  20. return &Color{}
  21. }
  22. // PaddingColorTo8 将color补充到8位,最后两位位Alpha
  23. func PaddingColorTo8(color string) string {
  24. hexColor := strings.Replace(color, "#", "", 1)
  25. strRune := []rune(hexColor)
  26. var strBuild strings.Builder
  27. if len(hexColor) == 3 {
  28. for i := 0; i < 3; i++ {
  29. strBuild.WriteString(string(strRune[i]))
  30. strBuild.WriteString(string(strRune[i]))
  31. }
  32. strBuild.WriteString("00")
  33. hexColor = strBuild.String()
  34. }
  35. if len(hexColor) > 8 {
  36. hexColor = util.CutString(hexColor, 0, 8)
  37. }
  38. strBuild.WriteString(hexColor)
  39. if len(hexColor) < 8 {
  40. padding := 8 - len(hexColor)
  41. for i := 0; i < padding; i++ {
  42. strBuild.WriteString("0")
  43. }
  44. }
  45. return strBuild.String()
  46. }
  47. // Alpha rgb alpha 0 透明 -> 1 不透明
  48. func Alpha(color string) (string, Color, float64) {
  49. // 0 透明 -> 1 不透明
  50. opacity := 1.0
  51. hexColor := PaddingColorTo8(color)
  52. color = util.CutString(hexColor, 0, 6)
  53. alpha := util.CutString(hexColor, 6, 8)
  54. hexAlpha, _ := strconv.ParseInt(alpha, 16, 10)
  55. opacity = float64(int((float64(hexAlpha)/255)*100)) / 100
  56. color = fmt.Sprintf("#%s", color)
  57. var rgb Color
  58. rgbRune := []rune(hexColor)
  59. r, _ := strconv.ParseInt(string(rgbRune[0:2]), 16, 10)
  60. rgb.Red = uint32(r)
  61. R, _ := strconv.ParseUint(string(rgbRune[0:2]), 16, 8)
  62. rgb.R = uint8(R)
  63. g, _ := strconv.ParseInt(string(rgbRune[2:4]), 16, 10)
  64. rgb.Green = uint32(g)
  65. G, _ := strconv.ParseUint(string(rgbRune[2:4]), 16, 8)
  66. rgb.G = uint8(G)
  67. b, _ := strconv.ParseInt(string(rgbRune[4:6]), 16, 10)
  68. rgb.Blue = uint32(b)
  69. B, _ := strconv.ParseUint(string(rgbRune[4:6]), 16, 8)
  70. rgb.G = uint8(B)
  71. a, _ := strconv.ParseInt(string(rgbRune[6:8]), 16, 10)
  72. rgb.Alpha = uint32(a / 255)
  73. A, _ := strconv.ParseUint(string(rgbRune[6:8]), 16, 8)
  74. rgb.A = uint8(A)
  75. return color, rgb, opacity
  76. }
  77. // Pixel PixelWand
  78. func Pixel(color string) *gmagick.PixelWand {
  79. destColor, _, opacity := Alpha(color)
  80. g := gmagick.NewPixelWand()
  81. g.SetColor(destColor)
  82. g.SetOpacity(opacity)
  83. return g
  84. }