Generating text based avatar images in C#

For one of my projects I needed a way to generate unique avatars for my users, while retaining lots of control over the visual. The avatars will be displayed in a public setting, so I couldn’t risk pulling in inappropriate images from elsewhere.

While there are some existing options such as Gravatar and RoboHash, neither was appropriate for what I needed so I decided to roll my own.

In the spirit of keeping things simple, I noticed the Outlook mail client on mobile generates an avatar image with the first and last initials of the person that sent the email (sorry about the blurry image):

This is ideal for my scenario!

First, to find some complementary background colours for the image.

A visit to one of my favourite sites yielded 5 complementary colour values that I stored in an array:

private List<string> _BackgroundColours = new List<string> { "3C79B2", "FF8F88", "6FB9FF", "C0CC44", "AFB28C" }; }

Then for each user I took their initials:

var avatarString = string.Format("{0}{1}", firstName[0], lastName[0]).ToUpper();

Selected a random background colour from the array:

var randomIndex = new Random().Next(0, _BackgroundColours.Count - 1);
var bgColour = _BackgroundColours[randomIndex];

Then composed them into a bitmap of size 192x192px:

var bmp = new Bitmap(192, 192);
var sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;

var font = new Font("Arial", 48, FontStyle.Bold, GraphicsUnit.Pixel);
var graphics = Graphics.FromImage(bmp);

graphics.Clear((Color)new ColorConverter().ConvertFromString("#" + bgColour));
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
graphics.DrawString(avatarString, font, new SolidBrush(Color.WhiteSmoke), new RectangleF(0, 0, 192, 192), sf);

From here it’s just a matter of saving the Bitmap to a stream somewhere, ie:

bmp.Save(stream, ImageFormat.Png)

And I end up with an image of my initials:

I use code similar to what I’ve described here in a service within an ASP.NET MVC5 web role on Azure. It could probably run elsewhere with a few minor changes.

Here’s a Gist with what should be a mostly reusable class (make sure to add a reference to System.Drawing), enjoy!