2019-09-26 07:01:17 +00:00
|
|
|
package identicon
|
|
|
|
|
|
|
|
import (
|
2020-02-10 11:22:37 +00:00
|
|
|
"crypto/md5" // nolint: gosec
|
2019-09-26 07:01:17 +00:00
|
|
|
"image/color"
|
2020-01-02 09:10:19 +00:00
|
|
|
|
2020-02-10 11:22:37 +00:00
|
|
|
"github.com/lucasb-eyer/go-colorful"
|
2019-09-26 07:01:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
defaultSaturation = 0.5
|
|
|
|
defaultLightness = 0.7
|
|
|
|
)
|
|
|
|
|
|
|
|
type Identicon struct {
|
|
|
|
bitmap []byte
|
|
|
|
color color.Color
|
|
|
|
}
|
|
|
|
|
|
|
|
func generate(key string) Identicon {
|
2020-02-10 11:22:37 +00:00
|
|
|
hash := md5.Sum([]byte(key)) // nolint: gosec
|
2019-09-26 07:01:17 +00:00
|
|
|
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]
|
2020-02-10 11:22:37 +00:00
|
|
|
sum := float64(h[13]) + float64(h[14]) + float64(h[15])
|
2019-09-26 07:01:17 +00:00
|
|
|
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
|
|
|
|
}
|