Captcha in ASP.NET


To reduce the incidence of spam and reduce the likelihood of denial of service attacks, many web pages include an image block with distorted text, known as a Captcha.

Captcha is an image with a code written on it. The website visitor is required to read the code on the image and enter the value in a text field. If the word entered is wrong, the form submission is not processed. As CAPTCHA is a smartly blurred image, the spam bot can't read it. So the form cannot be auto-submitted by a 'bot'.

This article will give step by step tutorial how to create Capcta in ASP.Net using c#.

STEP 1

Create Dynamic Images as per the Image size.

       private void GenerateImage()
        {
            // Create a new 32-bit bitmap image.
            Bitmap bitmap = new Bitmap(this.m_width, this.m_height,
            PixelFormat.Format32bppArgb);

            // Create a graphics object for drawing.
            Graphics g = Graphics.FromImage(bitmap);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle rect = new Rectangle(0, 0, this.m_width, this.m_height);

            // Fill in the background.
            HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti,
            Color.LightGray, Color.White);
            g.FillRectangle(hatchBrush, rect);

            // Set up the text font.
            SizeF size = default(SizeF);
            float fontSize = rect.Height + 1;
            Font font = default(Font);
            // Adjust the font size until the text fits within the image.
            do
            {
                fontSize -= 1;
                font = new Font(this.familyName, fontSize, FontStyle.Bold);
                size = g.MeasureString(this.m_text, font);
            } while (size.Width > rect.Width);

            // Set up the text format.
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            // Create a path using the text and warp it randomly.
            GraphicsPath path = new GraphicsPath();
            path.AddString(this.m_text, font.FontFamily, Convert.ToInt32(font.Style), font.Size, rect, format);
            float v = 4f;
            PointF[] points = {
              new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
              new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
              new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
              new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
       };
            Matrix matrix = new Matrix();
            matrix.Translate(0f, 0f);
            path.Warp(points, rect, matrix, WarpMode.Perspective, 0f);

            // Draw the text.
            hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
            g.FillPath(hatchBrush, path);

            // Add some random noise.
            int m = Math.Max(rect.Width, rect.Height);
            for (int i = 0; i <= Convert.ToInt32(Math.Truncate(rect.Width * rect.Height / 30f)) - 1; i++)
            {
                int x = this.random.Next(rect.Width);
                int y = this.random.Next(rect.Height);
                int w = this.random.Next(m / 50);
                int h = this.random.Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }

            // Clean up.
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();

            // Set the image.
            this.m_image = bitmap;
        }

Step 2

Create a ASP.Net webform Page to generate CapctaImage and this page will be refered as Image src in calling page

            CaptchaImage.CaptchaImage ci = new CaptchaImage.CaptchaImage(this.Session("CaptchaImageText").ToString(), 200, 50, "Arial black");

            // Change the response headers to output a JPEG image.
            this.Response.Clear();
            this.Response.ContentType = "image/jpeg";

            // Write the image to the response stream in JPEG format.
            ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
 
            // Dispose of the CAPTCHA image object.
            ci.Dispose();
        }

 

Many of these properties have to do with the inherent tradeoff between human readability and machine readability. The harder a CAPTCHA is for OCR software to read, the harder it will be for us human beings, too! For illustration, compare these two CAPTCHA images:

 Capcta in ASP.Net

Download the source code for more details.