Get Captcha Image c#

Get Captcha Image c#

public FileResult GetCaptchaImage()
        {
            MemoryStream ms = new MemoryStream();
            if (Session["CAPTCHA"] != null)
            {
                string text = Session["CAPTCHA"].ToString();
                //first, create a dummy bitmap just to get a graphics object
                Image img = new Bitmap(1, 1);
                Graphics drawing = Graphics.FromImage(img);
                Font font = new Font("Arial", 15);
                //measure the string to see how big the image needs to be
                SizeF textSize = drawing.MeasureString(text, font);
                //free up the dummy image and old graphics object
                img.Dispose();
                drawing.Dispose();
                //create a new image of the right size
                img = new Bitmap((int)textSize.Width + 40, (int)textSize.Height + 20);
                drawing = Graphics.FromImage(img);
                Color backColor = Color.SeaShell;
                Color textColor = Color.Red;
                //paint the background
                drawing.Clear(backColor);
                //create a brush for the text
                Brush textBrush = new SolidBrush(textColor);
                drawing.DrawString(text, font, textBrush, 20, 10);
                drawing.Save();
                font.Dispose();
                textBrush.Dispose();
                drawing.Dispose();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                img.Dispose();
                return File(ms.ToArray(), "image/png");
            }
            else
            {
                return File(ms.ToArray(), "image/png");
            }
        }

2020-01-31