Generate Captcha in Asp.net C#

Generating Captcha with image in C# 

Below is the method used to make image and Store it in CaptchaImage folder.The image name will be saved in Table using store procedure SP_InserCaptcha


 public dynamic GenrateCaptcha()
{
 
    string otp = Numbergenerate();
    string text = otp;
    Bitmap bitmap = new Bitmap(1, 1);
    Font font = new Font("Arial", 25, FontStyle.Regular, GraphicsUnit.Pixel);
    Graphics graphics = Graphics.FromImage(bitmap);
    int width = (int)graphics.MeasureString(text, font).Width;
    int height = (int)graphics.MeasureString(text, font).Height;
    bitmap = new Bitmap(bitmap, new Size(width, height));
    graphics = Graphics.FromImage(bitmap);
    graphics.Clear(Color.White);
    graphics.SmoothingMode = SmoothingMode.AntiAlias;
    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
    graphics.DrawString(text, font, new SolidBrush(Color.FromArgb(255, 0, 0)), 0, 0);
    graphics.Flush();
    graphics.Dispose();
    string fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";

    bitmap.Save(HttpContext.Current.Server.MapPath("~/CaptchaImage/") + fileName, ImageFormat.Jpeg);

    var data = db.SP_InserCaptcha(otp, fileName);

    return otp;
 
}

Numbergenerate method generate random which will be used as captcha in image.It can be any digit.it will be great if we use alphanumeric captcha.

 public string Numbergenerate()
        {
            string alphabets = "ABCDEFGHIJKLMNABCDEFGHIJKLMNPQRSTUVWXYZ";
            string numbers = "123456789";
            string characters = numbers;
            characters += alphabets + numbers;
            int length = 6;
            string otp = string.Empty;
            for (int i = 0; i < length; i++)
            {
                string character = string.Empty;
                do
                {
                    int index = new Random().Next(0, characters.Length);
                    character = characters.ToCharArray()[index].ToString();
                }
                while (otp.IndexOf(character) != -1);
                otp += character;
            }
            return otp;
        }

Below is the store procedure used in SQL to save captcha image and captcha with uniqe captcha id which will be used later to validate captcha

Create Proc SP_InserCaptcha    
(@Otp nvarchar(8),@CaptchaImg nvarchar(max))      
as      
begin      
if((select count(Captcha) from TblCaptcha) =1000)    
Truncate table TblCaptcha      
Insert Into TblCaptcha (Captcha,CatchaImage) values(@Otp,@CaptchaImg)      
select top(1)CaptchaID,CatchaImage from TblCaptcha    
order by CaptchaID desc    
   
end

Here is the table that is used to store captcha with captcha id.


CREATE TABLE [dbo].[TblCaptcha](
    [CaptchaID] [int] IDENTITY(1,1) NOT NULL,
    [CatchaImage] [nvarchar](64) NULL,
    [Captcha] [nvarchar](64) NULL)