Wednesday, November 3, 2010

Generate captcha image in asp.net - simple way

When it comes to captcha images simple question pops in i.e. how to generate captcha images?
This article is about generating Captcha image in asp.net, this is very simple logic which can be implemented immediately for any website. You can directly Download Demo and use it.
We have used following simple steps to Generate Captcha Image in asp.net
  1. Create Captcha Image from random numbers and store that number in session variable, we have used Captcha.aspx page for the same.
  2. Use Captcha.aspx as source for the captcha image in Default.aspx page, i.e. for image tag give Captcha.aspx as SRC.
  3. On Submit click simply verify captcha entered by user and captcha in session. 
Our folder structure is very simple, check out following image


To understand the way we have checked captcha, have look on HTML of Default.aspx page (Check out DemoCode, for better understanding.)


Catptcha Text



Check out the way we have used Captcha.aspx page in image source.

On submit click we simply checks whether Captcha entered in "txtCaptcha" is valid or not, we have following code for submit button clicked.

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["Captcha"] != null)
        {
            if (txtCaptcha.Text == Session["Captcha"].ToString())
            {
                Response.Redirect("RedirectPage.aspx");
            }
            else
            {
                Response.Write("Please Enter Valid Captcha code");
                txtCaptcha.Text = "";
            }
        }
        else
        {
            Response.Write("Session Expired, please re-enter Captcha.");
        }
    }

Now what remains is the logic for Generate captcha image, we don't have any HTML tags on captcha.aspx, we simply write following code for Binary Image Generation and write it. We have used Random number; but we can have our different logic for the same.

protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";
        Random random = new Random(DateTime.Now.Millisecond);

        int number = random.Next(100000);

        Session.Add("Captcha",number.ToString());

        System.Drawing.Bitmap bmpOut = new Bitmap(100, 50);

        Graphics graphics = Graphics.FromImage(bmpOut);

        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;

        graphics.FillRectangle(Brushes.Aquamarine, 0, 0, 100, 50);

        graphics.DrawString(number.ToString(), new Font("TimesNewRoman", 20), new SolidBrush(Color.Coral), 0, 0);

        MemoryStream memorystream = new MemoryStream();

        bmpOut.Save(memorystream, System.Drawing.Imaging.ImageFormat.Png);

        byte[] bmpBytes = memorystream.GetBuffer();

        bmpOut.Dispose();

        memorystream.Close();

        Response.BinaryWrite(bmpBytes);

        Response.End();

    }

Thats it we are done with our Generate captcha image in asp.net. Very simple code to use, download democode and use it directly in your web application.

Download Democode here---> CaptchaInAsp.net.zip
Submit this story to DotNetKicks

0 comments: