identicon

package module
v0.0.0-...-d5ba358 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2024 License: MIT Imports: 12 Imported by: 3

README

IdentIcon

CircleCI Go Report Card

IdentIcon is an open source avatar generator inspired by GitHub avatars.

IdentIcon uses a deterministic algorithm that generates an image (using Golang's stdlib image encoders) based on a text (Generally Usernames, Emails or just random strings), by hashing it and iterating over the bytes of the digest to pick whether to draw a point, pick a color or choose where to go next.

IdentIcon's Generator enables the creation of customized figures: (NxN size, points density, custom color palette) as well as multiple exporting formats in case the developers want to generate their own images.

Installation

$ go get github.com/rrivera/identicon

Usage


import (
    "os"

    "github.com/rrivera/identicon"
)

// New Generator: Rehuse 
ig, err := identicon.New(
    "github", // Namespace
    5,        // Number of blocks (Size)
    3,        // Density
)

if err != nil {
    panic(err) // Invalid Size or Density
}

username := "rrivera"      // Text - decides the resulting figure
ii, err := ig.Draw(username) // Generate an IdentIcon

if err != nil {
    panic(err) // Text is empty
}

// File writer
img, _ := os.Create("icon.png")
defer img.Close()
// Takes the size in pixels and any io.Writer
ii.Png(300, img) // 300px * 300px

Examples

5x5
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
7x7
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
10x10
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo
rrivera johndoe abc123 modulo

View examples

Documentation

Changelog

Contribution

License

MIT

Copyright (c) 2018-present, Ruben Rivera

Documentation

Overview

Package identicon is an open source avatar generator inspired by GitHub avatars.

IdentIcon uses a deterministic algorithm that generates an image (using Golang's stdlib image encoders) based on a text (Generally Usernames, Emails or just random strings), by hashing it and iterating over the bytes of the digest to pick whether to draw a point, pick a color or choose where to go next.

IdentIcon's Generator enables the creation of customized figures: (NxN size, points density, custom color palette) as well as multiple exporting formats in case the developers want to generate their own images.

Example
package main

import (
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New(
		"github.com", // namespace
		5,            // number of blocks (size)
		2,            // density of points
	)

	if err != nil {
		panic(err)
	}

	username := "rrivera"
	ii, err := ig.Draw(username) // Generate an IdentIcon

	if err != nil {
		panic(err)
	}

	// File writer
	// img, _ := os.Create("./examples/" + username + ".png")
	// defer img.Close()
	// Takes the size in pixels and an io.Writer
	// ii.Png(300, img) // 300px * 300px

	fmt.Println(ii.String(" ", "."))
}
Output:

. . . . .
1 1 1 1 1
1 . 1 . 1
. . 2 . .
. . . . .

Index

Examples

Constants

View Source
const (
	// MinSize is the minimal number of blocks allowed, anything lower that this
	// wouldn't make sense.
	MinSize = 4
)

Constrains for the size of the IdentIcon.

Variables

This section is empty.

Functions

func SetBackgroundColorFunction

func SetBackgroundColorFunction(bcf func([]byte, color.Color) color.Color) option

SetBackgroundColorFunction replaces the default background's color generation function (HSL).

func SetFillColorFunction

func SetFillColorFunction(fcf func([]byte) color.Color) option

SetFillColorFunction replaces the default color generation function (HSL).

func SetHashFunction

func SetHashFunction(hf func([]byte) []byte) option

SetHashFunction replaces the default hash function (Sha256).

func SetRandom

func SetRandom(r bool) option

SetRandom to append a random string to the generator text everytime Draw is called.

Types

type Canvas

type Canvas struct {
	// Size same value specified in identicon.New(...).
	Size int
	// PointsMap contains all coordinates and it's values that form the figure.
	PointsMap map[int]map[int]int
	// MinY is the upper Y-axis that has at least one point drawn.
	MinY int
	// MaxY is the lower Y-axis that has at least one point drawn.
	MaxY int
	// VisitedYPoints contains all Y-axis that had been visited. Helpful to
	// determine big blank spaces in the resulting figure.
	VisitedYPoints map[int]bool
	// FilledPoints is the number of points filled at least once.
	FilledPoints int
}

Canvas contains what is needed to generate an image. It contains properties that could be useful when rendering the image.

  • Having MinY and MaxY allows you to vertically center the figure.
  • VisitedYPoints could be useful to determine whether there is a big empty vertical space in the figure.

func (*Canvas) Array

func (c *Canvas) Array() [][]int

Array generates a two-dimensional array version of the IdentIcon figure.

func (*Canvas) IntCoordinates

func (c *Canvas) IntCoordinates() [][]int

IntCoordinates generates an array of points of a two-dimensional plane as:

  • [x, y] that correspond to all filled points in the IdentIcon figure.

func (*Canvas) Points

func (c *Canvas) Points() []image.Point

Points generates an array of points of a two-dimensional plane as [x, y] that correspond to all filled points in the IdentIcon figure.

func (*Canvas) String

func (c *Canvas) String(separator string, fillEmptyWith string) string

ToString generates a string version of the IdentIcon figure.

type Generator

type Generator struct {
	// Namespace that will be concatenated previous to the icon generation.
	Namespace string
	// Size is the number of blocks of the figure.
	Size int
	// Density * Size = times to iterate over the hash of Text:Namespace:Seed.
	Density int
	// contains filtered or unexported fields
}

Generator represents a predefined set of configurations that can be reused to create multiple icons by passing a Text string only.

func New

func New(
	namespace string,
	size int,
	density int,
	opts ...option,
) (*Generator, error)

New returns a pointer to a Generator with the desired configuration.

Example (CustomOptions)
package main

import (
	"image/color"

	"github.com/rrivera/identicon"
)

func main() {

	alwaysRed := func(cb []byte) color.Color {
		return color.RGBA{255, 0, 0, 255}
	}

	transparentBg := func(cb []byte, fc color.Color) color.Color {
		return color.Transparent
	}

	ig, _ := identicon.New(
		"",
		7,
		4,
		identicon.SetRandom(true), // Resultant image will be random
		identicon.SetFillColorFunction(alwaysRed),           // Points will be red
		identicon.SetBackgroundColorFunction(transparentBg), // Background will be transparent
	)

	// All generated IdentIcons will match configuration (fill=red, bg=transparent, isRandom=true)
	ig.Draw("rrivera")
	ig.Draw("username")
	ig.Draw("admin")

}
Output:

func (Generator) Draw

func (g Generator) Draw(text string) (*IdentIcon, error)

Draw returns a pointer to an IdentIcon with a generated figure and a color.

Example (Size7x7withNamespace)
package main

import (
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New(
		"null.rocks",
		7,
		4,
	)

	if err != nil {
		panic(err)
	}

	username := "admin"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	fmt.Println(ii.GeneratorText())
	fmt.Println(ii.String(" ", "."))
}
Output:

admin:null.rocks
. 1 2 . 2 1 .
. 2 . . . 2 .
. . . 1 . . .
. . . 1 . . .
2 . . 4 . . 2
. . 4 2 4 . .
. 1 2 1 2 1 .

func (*Generator) Option

func (g *Generator) Option(opts ...option)

Option sets the options specified.

type HSL

type HSL struct {
	// Hue [0, 360]
	H uint32
	// Saturation [0, 100]
	S uint32
	// Lightness [0, 100]
	L uint32
}

HSL is a color model representation based on RGB. HSL facilitates the generation of colors that look similar between themselves by changing the value of Hue H while keeping Saturation S and Lightness L the same.

func (HSL) RGBA

func (hsl HSL) RGBA() (r, g, b, a uint32)

RGBA conversion

type IdentIcon

type IdentIcon struct {
	// Text is the base string that will generate the canvas after being hashed.
	Text string
	// Namespace
	Namespace string

	// Size is the number of blocks of the figure.
	Size int
	// Density * Size = times to iterate over the hash of Text.
	Density int
	// Canvas is a map of maps that contains the points and values that has been
	// visited and filled.
	Canvas Canvas

	// FillColor is the color used to fill squares in the figure when encoding
	// to PNG or JPEG.
	FillColor color.Color
	// BackgroundColor is the background color of the figure when encoding it to
	// PNG or JPEG.
	BackgroundColor color.Color
	// contains filtered or unexported fields
}

IdentIcon represents a mirror-symmetry image generated from a string and a set of configurations.

func (*IdentIcon) Array

func (ii *IdentIcon) Array() [][]int

Array generates a two-dimensional array version of the IdentIcon figure.

Example
package main

import (
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("github.com", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "rrivera"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	// Array representation of the IdentIcon
	arr := ii.Array()
	fmt.Print(arr)
}
Output:

[[3 1 0 2 0 1 3] [5 1 0 1 0 1 5] [2 2 0 0 0 2 2] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0] [1 0 2 1 2 0 1]]

func (*IdentIcon) Draw

func (ii *IdentIcon) Draw()

Draw a figure in Canvas.

  • If isRandom == true, the figure will redrawn everytime Draw() is called,
  • If isRandom == false and Draw() was called before, it won't redraw.

func (*IdentIcon) GeneratorText

func (ii *IdentIcon) GeneratorText() string

GeneratorText returns the string later to be hashed using the format:

  • Text[:Namespace][:randomSeed]
Example
package main

import (
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("namespace", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "text"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	fmt.Print(ii.GeneratorText())
}
Output:

text:namespace

func (*IdentIcon) Image

func (ii *IdentIcon) Image(pixels int) image.Image

Image genetares an image.Image of size

func (*IdentIcon) IntCoordinates

func (ii *IdentIcon) IntCoordinates() [][]int

IntCoordinates generates an array of points of a two-dimensional plane as:

  • [x, y] that correspond to all filled points in the IdentIcon figure.

func (*IdentIcon) Jpeg

func (ii *IdentIcon) Jpeg(pixels int, quality int, w io.Writer) error

Jpeg writes an image of pixels and quality

Example
package main

import (
	"os"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "yourUsername"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	// File writer
	img, _ := os.Create("./examples/" + username + ".jpg")
	defer img.Close()

	quality := 90

	// Takes the size in pixels, quality and an io.Writer
	ii.Jpeg(300, quality, img) // 300px * 300px
}
Output:

func (*IdentIcon) Png

func (ii *IdentIcon) Png(pixels int, w io.Writer) error

Png writes an image of pixels

Example
package main

import (
	"os"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "yourUsername"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	// File writer
	img, _ := os.Create("./examples/" + username + ".png")
	defer img.Close()
	// Takes the size in pixels and an io.Writer
	ii.Png(300, img) // 300px * 300px
}
Output:

Example (Base64Encoded)
package main

import (
	"bytes"
	"encoding/base64"
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "yourUsername"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	// File writer
	out := new(bytes.Buffer)
	// Takes the size in pixels and an io.Writer
	ii.Png(300, out) // 300px * 300px

	str := base64.StdEncoding.EncodeToString(out.Bytes())
	fmt.Println(str)
}
Output:

iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAIAAAD2HxkiAAAD1UlEQVR4nOzVsY2dUBBA0cX6rVAE/VAW/VAETUwJlrMNLMJ/kTgnJZjhSVfzmZkfoPOnXgDeToQQEyHERAgxEUJMhBATIcRECDERQuxz//na9m9t8gjreSRzq3d+2/9W7t/ZJYSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQogtM1Pv8CDXttcrvMJ6HvUKD+ISQkyEEBMhxEQIMRFCTIQQEyHERAgxEUJMhBATIcRECDERQkyEEBMhxEQIMRFCTIQQEyHERAgxEUJMhBATIcRECDERQkyEEBMhxEQIMRFCTIQQEyHERAgxEUJMhBATIcRECDERQkyEEBMhxJaZqXfg59r2ZO56HslcfnMJISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYp96gf+7tr1e4avW80jmeucncAkhJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiy8zcfL62/YvL9NbzSOZW7/y2/63cv7NLCDERQkyEEBMhxEQIMRFCTIQQEyHERAgxEUJMhBATIcRECDERQkyEEBMhxEQIMRFCTIQQEyHERAgxEUJMhBATIcRECDERQkyEEBMhxEQIMRFCTIQQEyHERAgxEUJMhBATIcRECDERQkyEEFtmpt4BXs0lhJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiH3qBfjn2vZk7noeyVx+cwkhJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiIoSYCCEmQoiJEGIihJgIISZCiIkQYiKEmAghJkKIiRBiy8zUO8CruYQQEyHERAgxEUJMhBATIcRECDERQkyEEPsbAAD//6PdNDxqoCsvAAAAAElFTkSuQmCC

func (*IdentIcon) Points

func (ii *IdentIcon) Points() []image.Point

Points generates an array of points of a two-dimensional plane as [x, y] that correspond to all filled points in the IdentIcon figure.

Example
package main

import (
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("github.com", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "userName123"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	// Array of image.Points representation of the IdentIcon
	ps := ii.Points()
	fmt.Print(ps)
}
Output:

func (*IdentIcon) String

func (ii *IdentIcon) String(separator string, fillEmptyWith string) string

ToString generates a string version of the IdentIcon figure.

Example
package main

import (
	"fmt"

	"github.com/rrivera/identicon"
)

func main() {
	ig, err := identicon.New("github.com", 7, 4)

	if err != nil {
		panic(err)
	}

	username := "userName12345"
	ii, err := ig.Draw(username)

	if err != nil {
		panic(err)
	}

	// String representation of the IdentIcon
	// separator = " "
	// fill empty blocks = "."
	str := ii.String(" ", ".")
	fmt.Print(str)
}
Output:

. 2 4 . 4 2 .
1 1 . . . 1 1
. . 2 2 2 . .
1 . . 1 . . 1
. . . . . . .
. . . . . . .
. 2 1 1 1 2 .

func (*IdentIcon) Svg

func (ii *IdentIcon) Svg(pixels int, w io.Writer) error

Svg writes an image of pixels

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL