-
Notifications
You must be signed in to change notification settings - Fork 244
/
identicon.go
61 lines (51 loc) · 1.09 KB
/
identicon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package identicon
import (
"crypto/md5" // nolint: gosec
"image/color"
"github.com/lucasb-eyer/go-colorful"
)
const (
defaultSaturation = 0.5
defaultLightness = 0.7
)
type Identicon struct {
bitmap []byte
color color.Color
}
func generate(key string) Identicon {
hash := md5.Sum([]byte(key)) // nolint: gosec
return Identicon{
convertPatternToBinarySwitch(generatePatternFromHash(hash)),
getColorFromHash(hash),
}
}
func getColorFromHash(h [16]byte) color.Color {
// Take the last 3 relevant bytes, and convert to a float between [0..360]
sum := float64(h[13]) + float64(h[14]) + float64(h[15])
t := (sum / 765) * 360
return colorful.Hsl(t, defaultSaturation, defaultLightness)
}
func generatePatternFromHash(sum [16]byte) []byte {
p := make([]byte, 25)
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
jCount := j
if j > 2 {
jCount = 4 - j
}
p[5*i+j] = sum[3*i+jCount]
}
}
return p
}
func convertPatternToBinarySwitch(pattern []byte) []byte {
b := make([]byte, 25)
for i, v := range pattern {
if v%2 == 0 {
b[i] = 1
} else {
b[i] = 0
}
}
return b
}