diff --git a/README.md b/README.md index 516a5ef..77aac7b 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ type Options struct { Font *truetype.Font Palette []color.Color LetterColor color.Color + PaletteKey string } ``` @@ -34,6 +35,10 @@ img, err := letteravatar.Draw(100, 'A', &letteravatar.Options{ }) ``` +## Documentation + +[https://godoc.org/github.com/disintegration/letteravatar](https://godoc.org/github.com/disintegration/letteravatar) + ## Examples ![](example/Alice.png) @@ -103,3 +108,5 @@ func main() { The package "letteravatar" is distributed under the terms of the MIT license. The Roboto-Medium font is distributed under the terms of the Apache License v2.0. + +See [LICENSE](LICENSE). \ No newline at end of file diff --git a/draw.go b/draw.go index 4f8df87..629804a 100644 --- a/draw.go +++ b/draw.go @@ -19,6 +19,11 @@ type Options struct { Font *truetype.Font Palette []color.Color LetterColor color.Color + + // PaletteKey is used to pick the background color from the Palette. + // Using the same PaletteKey leads to the same background color being picked. + // If PaletteKey is empty (default) the background color is picked randomly. + PaletteKey string } var defaultLetterColor = color.RGBA{0xf0, 0xf0, 0xf0, 0xf0} @@ -43,7 +48,11 @@ func Draw(size int, letter rune, options *Options) (image.Image, error) { var bgColor color.Color = color.RGBA{0x00, 0x00, 0x00, 0xff} if len(palette) > 0 { - bgColor = palette[randint(len(palette))] + if options != nil && len(options.PaletteKey) > 0 { + bgColor = palette[keyindex(len(palette), options.PaletteKey)] + } else { + bgColor = palette[randint(len(palette))] + } } return drawAvatar(bgColor, letterColor, font, size, letter) @@ -100,6 +109,14 @@ func newRGBA(w, h int, c color.Color) *image.RGBA { return img } +func keyindex(n int, key string) int { + var index int64 + for _, r := range key { + index = (index + int64(r)) % int64(n) + } + return int(index) +} + var ( rng = rand.New(rand.NewSource(time.Now().UnixNano())) rngMu = new(sync.Mutex) diff --git a/draw_test.go b/draw_test.go index 850c3dc..ac9d1b8 100644 --- a/draw_test.go +++ b/draw_test.go @@ -70,6 +70,33 @@ func TestDraw(t *testing.T) { } } +func TestPaletteKey(t *testing.T) { + users := []string{ + "Username 1", + "Username 2", + "Username 3", + "Username 4", + "Username 5", + } + avatars := make(map[string]image.Image) + for _, u := range users { + img, err := Draw(30, []rune(u)[0], &Options{PaletteKey: u}) + if err != nil { + t.Fatalf("failed to create avatar for %s: %s", u, err) + } + avatars[u] = img + } + for _, u := range users { + img, err := Draw(30, []rune(u)[0], &Options{PaletteKey: u}) + if err != nil { + t.Fatalf("failed to create avatar for %s: %s", u, err) + } + if !reflect.DeepEqual(avatars[u], img) { + t.Fatalf("avatar mismatch for %s: %#v, %#v", avatars[u], img) + } + } +} + func compareImages(img1, img2 image.Image) float64 { if !img1.Bounds().Eq(img2.Bounds()) { return 0