Wednesday, November 3, 2010

Generate captcha image in - 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, 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
  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.Write("Please Enter Valid Captcha code");
                txtCaptcha.Text = "";
            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);


        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();






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

Download Democode here--->
Submit this story to DotNetKicks