I want to create a default avatar image which is a circle with initials in it. I want to do this on the server side as a png. Is this possible using the .net graphics library?
Asked
Active
Viewed 4,974 times
6
-
There is no single ".NET graphics library", there are several. For example, [`System.Drawing`](https://msdn.microsoft.com/en-us/library/gg145023%28v=vs.110%29.aspx) and [`System.Windows.Media`](https://msdn.microsoft.com/en-us/library/system.windows.media%28v=vs.110%29.aspx) can be used largely independently of each other. – O. R. Mapper Feb 15 '15 at 15:04
-
I had only seen system.drawing but will look into system.windows.media. – Tija Feb 15 '15 at 15:07
-
1Of course. Create a Bitmap, draw/fill a Circle, maybe measure the string putput to place it nicely, then drawString the letters, save as Fileformat.Png. 5-10 lines. – TaW Feb 15 '15 at 15:09
-
1Does "on the server side" mean you are using ASP.NET? – nvoigt Feb 15 '15 at 15:09
-
1The answer to your question is quite simply "yes". Maybe you need to be more specific? – Feb 15 '15 at 16:20
-
Visit this link for helpful information about this topic [Create text avatar image (Rectangle and Circle)](http://stackoverflow.com/questions/33120224/set-default-user-profile-picture-to-an-image-of-their-initials/35326880#35326880) – Galaxy Starts Feb 10 '16 at 22:12
1 Answers
12
I ended up doing this. Thanks for pointing me in the right direction TaW
public ActionResult Avatar()
{
using (var bitmap = new Bitmap(50, 50))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.Clear(Color.White);
using (Brush b = new SolidBrush(ColorTranslator.FromHtml("#eeeeee")))
{
g.FillEllipse(b, 0, 0, 49, 49);
}
float emSize = 12;
g.DrawString("AM", new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
new SolidBrush(Color.Black), 10, 15);
}
using (var memStream = new System.IO.MemoryStream())
{
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);
var result = this.File(memStream.GetBuffer(), "image/png");
return result;
}
}
}

Tija
- 1,691
- 4
- 20
- 33
-
Characters with a small width are not centered for example AI. I added this https://stackoverflow.com/questions/9722368/determining-text-width but switched to a CSS solution in the end. – Alex Jan 09 '23 at 15:21