Files
identicon-algorithms/main.go

76 lines
1.4 KiB
Go
Raw Normal View History

2026-02-24 17:34:02 +01:00
package main
import (
"crypto/sha1"
"fmt"
"strconv"
"github.com/fogleman/gg"
)
2026-02-24 18:20:30 +01:00
/*
8x8 square of 100x100 px squares
First 6 characters of the hash are the color
For the next 8 characters each character
represents 4 bits of a row being on or off.
The image is then mirrored to the right side.
9d26bf3cf1fb2b2f02d4a2013333f4fcd551cb2e
9d26bf -> color
3 -> row1
c -> row2
...
b -> row8
3 = 0 0 1 1
c = 1 1 0 0
...
b = 1 0 1 1
*/
2026-02-24 17:34:02 +01:00
func main() {
dc := gg.NewContext(800, 800)
2026-02-24 18:20:30 +01:00
hash := hash("Jaybee18")
2026-02-24 17:34:02 +01:00
colorString := hash[0:6]
r, g, b := rgbFromHex(colorString)
dc.SetRGB255(r, g, b)
for i, character := range hash[6:14] {
2026-02-24 18:20:30 +01:00
integer, _ := strconv.ParseUint(string(character), 16, 4)
for j := range 4 {
on := hasBit(integer, j)
2026-02-24 17:34:02 +01:00
2026-02-24 18:20:30 +01:00
dc.DrawRectangle(float64(j * 100), float64(i * 100), 100, 100)
dc.DrawRectangle(700 - float64(j * 100), float64(i * 100), 100, 100)
2026-02-24 17:34:02 +01:00
if !on {
dc.SetRGB255(r, g, b)
} else {
dc.SetRGB255(255, 255, 255)
}
dc.Fill()
}
}
dc.SavePNG("out.png")
}
func rgbFromHex(hex string) (int, int, int) {
r, _ := strconv.ParseUint(hex[0:2], 16, 8)
g, _ := strconv.ParseUint(hex[2:4], 16, 8)
b, _ := strconv.ParseUint(hex[4:6], 16, 8)
return int(r), int(g), int(b)
}
func hash(str string) string {
h := sha1.New()
h.Write([]byte(str))
res := h.Sum(nil)
return fmt.Sprintf("%x", res)
}
2026-02-24 18:20:30 +01:00
func hasBit(n uint64, pos int) bool {
2026-02-24 17:34:02 +01:00
val := n & (1 << pos)
return (val > 0)
}