Dynamic Avatars in Go: A Step-by-Step Guide
Getting Started with Go
To create dynamic avatars for your users, you’ll need a recent version of Go installed (version 1.14 or higher). Create a new project folder and initialize a Go module using the following command:
go mod init go-avatars
Setting Up Dependencies
Add the necessary dependencies to your project by running the following command:
go get -u github.com/nfnt/resize github.com/golang/freetype/truetype github.com/go-chi/chi/v5
These dependencies include the image
package for working with images, freetype
for font rendering, and the chi
router for serving generated avatars over HTTP.
Creating the Avatar Canvas
Create a main.go
file and implement the createAvatar
function, which generates a square canvas with a uniform background color based on the provided HEX code.
go
func createAvatar(size int, initials string, color string) (*image.RGBA, error) {
//...
}
Converting HEX to RGBA
Implement the hexToRGBA
function to convert HEX color codes to their RGBA equivalents.
go
func hexToRGBA(hex string) (uint8, uint8, uint8, uint8) {
//...
}
Drawing Text on the Canvas
Implement the drawText
function to render the user’s initials on the avatar canvas.
go
func drawText(img *image.RGBA, text string) {
//...
}
Serving Avatars with Chi Router
Modify the main
function to serve generated avatars over HTTP using the chi
router.
go
func main() {
r := chi.NewRouter()
r.Get("/avatar", func(w http.ResponseWriter, r *http.Request) {
//...
})
http.ListenAndServe(":3000", r)
}
Putting it all Together
Run the main.go
file using go run./main.go
and visit http://localhost:3000/avatar?initials=JD&size=300
in your browser to see the generated avatar.
Taking it Further
Consider taking your dynamic avatars to the next level by using a background color determined by the user’s initials. One approach is to create a slice of hexadecimal color strings and pick a color based on the hash of the initials.
Check out the complete source code for this tutorial on GitLab, and explore a mini package based on this code that you can use in your own projects.