6

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?

6
  • There is no single ".NET graphics library", there are several. For example, System.Drawing and System.Windows.Media can be used largely independently of each other. Feb 15, 2015 at 15:04
  • I had only seen system.drawing but will look into system.windows.media.
    – Tija
    Feb 15, 2015 at 15:07
  • 1
    Of 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, 2015 at 15:09
  • 1
    Does "on the server side" mean you are using ASP.NET?
    – nvoigt
    Feb 15, 2015 at 15:09
  • 1
    The answer to your question is quite simply "yes". Maybe you need to be more specific?
    – user585968
    Feb 15, 2015 at 16:20

1 Answer 1

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;
                }
            }
        }
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.