CAPTCHA Code


Add new aspx page named captcha_image.aspx

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

public partial class CAPTCHA_Image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Drawing.Bitmap objbmp = null;
        System.Drawing.Graphics objgraphics = null;
        Font objFont = null;
        try
        {
            objbmp = new System.Drawing.Bitmap(60, 20);
            //objgraphics = New System.Drawing.Graphics;
            objgraphics = System.Drawing.Graphics.FromImage(objbmp);
            objgraphics.Clear(Color.Green);
            objgraphics.TextRenderingHint = objgraphics.TextRenderingHint;
            objFont = new Font("Arial", 10, FontStyle.Bold);
            string randomStr = "";
            int[] myIntArray = new int[6];
            int x = 0;
            Random autoRand = new Random();
            for (x = 0; x <= 4; x++)
            {
                myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9));
                randomStr += myIntArray[x].ToString();
            }
            Session.Add("randomStr", randomStr);
            // Write out the text 
            objgraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
            // Set the content type and return the image 
            Response.ContentType = "image/GIF";
            objbmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
        }
        finally
        {
            if ((objFont != null))
            {
                objFont.Dispose();
                objFont = null;
            }
            if ((objgraphics != null))
            {
                objgraphics.Dispose();
                objgraphics = null;
            }
            if ((objbmp != null))
            {
                objbmp.Dispose();
                objbmp = null;
            }
        }
    } 

}

Drag n Drop image icon from toolbox  to the  authenticatepage.aspx page on which you want to implement captcha. and add one textbox(txtcaptcha.text) Set the  imageUrl property = captcha_image.aspx

and write below code on the submit button

if (Page.IsValid && txtCaptcha.Text.ToString() == Session["randomStr"].ToString())
                    {
code
.
.
.
.
}
else
            {
                Label2.Text = "Please feed the Code correctly as shown.";
            }

Comments

Popular posts from this blog

show (value1,value2) in one column in sql