Refactor avatar package, support default avatar fallback (#36788)

* Fix #34715
This commit is contained in:
wxiaoguang
2026-03-01 21:32:35 +08:00
committed by GitHub
parent 1592576fa5
commit 2c624d4deb
15 changed files with 205 additions and 276 deletions
+12 -19
View File
@@ -8,13 +8,14 @@ package identicon
import (
"crypto/sha256"
"errors"
"fmt"
"image"
"image/color"
)
const minImageSize = 16
const (
minImageSize = 16
maxImageSize = 2048
)
// Identicon is used to generate pseudo-random avatars
type Identicon struct {
@@ -24,25 +25,17 @@ type Identicon struct {
rect image.Rectangle
}
// New returns an Identicon struct with the correct settings
// size image size
// back background color
// fore all possible foreground colors. only one foreground color will be picked randomly for one image
func New(size int, back color.Color, fore ...color.Color) (*Identicon, error) {
if len(fore) == 0 {
return nil, errors.New("foreground is not set")
}
if size < minImageSize {
return nil, fmt.Errorf("size %d is smaller than min size %d", size, minImageSize)
}
// New returns an Identicon struct.
// Only one foreground color will be picked randomly for one image.
func New(size int, backColor color.Color, foreColors []color.Color) *Identicon {
size = max(size, minImageSize)
size = min(size, maxImageSize)
return &Identicon{
foreColors: fore,
backColor: back,
foreColors: foreColors,
backColor: backColor,
size: size,
rect: image.Rect(0, 0, size, size),
}, nil
}
}
// Make generates an avatar by data
+1 -1
View File
@@ -23,7 +23,7 @@ func TestGenerate(t *testing.T) {
}
backColor := color.White
imgMaker, err := New(64, backColor, DarkColors...)
imgMaker, err := New(64, backColor, DarkColors)
assert.NoError(t, err)
for i := 0; i < 100; i++ {
s := strconv.Itoa(i)