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?
1 Answer
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;
}
}
}
-
Characters with a small width are not centered for example AI. I added this stackoverflow.com/questions/9722368/determining-text-width but switched to a CSS solution in the end.– AlexJan 9 at 15:21
System.Drawing
andSystem.Windows.Media
can be used largely independently of each other.