Add support for SVG identicons

This commit is contained in:
2024-05-20 18:03:43 +02:00
parent 5befff0716
commit a39fb686a3
6 changed files with 100 additions and 6 deletions

View File

@ -42,6 +42,29 @@ func (generator *GhIconGenerator) GenIcon(id string, size int) *image.NRGBA {
return drawImage(mirrorData(data, blocks), blocks, size, generator.colorGenerator(hash))
}
func (generator *GhIconGenerator) GenSvg(id string, size int) string {
if size > 512 {
size = 512
}
blocks := 5
hash := HashBytes(id)
nibbles := nibbles(hash)
data := make([]bool, blocks*blocks)
for x := 0; x < blocks; x++ {
for y := 0; y < blocks; y++ {
ni := x + blocks*(blocks-y-1)
if x+blocks*y >= 2*blocks {
di := (x + blocks*y) - 2*blocks
data[di] = nibbles[ni%32]%2 == 0
}
}
}
return drawSvg(mirrorData(data, blocks), blocks, size, generator.colorGenerator(hash))
}
// https://processing.org/reference/map_.html
func remap(value uint32, vmin uint32, vmax uint32, dmin uint32, dmax uint32) float32 {
return float32((value-vmin)*(dmax-dmin)) / float32((vmax-vmin)+dmin)

View File

@ -3,6 +3,7 @@ package icons
import (
"crypto/md5"
"encoding/hex"
"fmt"
"image"
"image/color"
"image/draw"
@ -12,6 +13,7 @@ import (
type IconGenerator interface {
GenIcon(id string, size int) *image.NRGBA
GenSvg(id string, size int) string
}
func HashBytes(id string) [16]byte {
@ -62,5 +64,37 @@ func drawImage(data []bool, blocks int, size int, c color.Color) *image.NRGBA {
}
}
drawSvg(data, blocks, size, c)
return img
}
func drawSvg(data []bool, blocks int, size int, c color.Color) string {
blockSize := size / (blocks + 1)
border := (size - (blocks * blockSize)) / 2
r, g, b, _ := c.RGBA()
colorHtml := fmt.Sprintf("#%x%x%x", r>>8, g>>8, b>>8)
blockElems := fmt.Sprintf("<rect style=\"fill:#f0f0f0\" width=\"%d\" height=\"%d\" x=\"0\" y=\"0\" />", size, size)
for x := 0; x < blocks; x++ {
for y := 0; y < blocks; y++ {
idx := x*blocks + y
if data[idx] {
blockElems += fmt.Sprintf(
`<rect style="fill:%s" width="%d" height="%d" x="%d" y="%d" />`,
colorHtml,
blockSize,
blockSize,
border+(x*blockSize),
border+(y*blockSize))
}
}
}
return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<svg width="%d" height="%d" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"><g>%s</g></svg>`,
size, size,
blockElems)
}

View File

@ -34,6 +34,21 @@ func (generator *IdIconGenerator) GenIcon(id string, size int) *image.NRGBA {
return drawImage(mirrorData(data, blocks), blocks, size, generator.colorGenerator(hash))
}
func (generator *IdIconGenerator) GenSvg(id string, size int) string {
id = strings.ToLower(id)
blocks := 5
if size > 512 {
size = 512
}
hash := HashBytes(id)
data := make([]bool, blocks*blocks)
for i := 0; i < len(hash)-1; i++ {
data[i] = hash[i]%2 != hash[i+1]%2
}
return drawSvg(mirrorData(data, blocks), blocks, size, generator.colorGenerator(hash))
}
func ColorV1(hash [16]byte) color.RGBA {
r := 32 + (hash[0]%16)/2<<4
g := 32 + (hash[2]%16)/2<<4