Sunday, 24 June 2012

Create a Captcha Image in C# .NET

Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart.)

The Captcha technology help you to make sure your site is reasonably secure against automated attacks.

Step:1 Write the following code in a class named CaptchaText.cs or you can download it here


public class CaptchaText
{
   public string Text
   {
     get { return this.text; }
   }
   public Bitmap Image
   {
     get { return this.image; }
   }
   public int Width
   {
     get { return this.width; }
   }
   public int Height
   {
     get { return this.height; }
   }

   private string text;
   private int width;
   private int height;
   private string familyName;
   private Bitmap image;
   private Random random = new Random();
   public CaptchaText(string s, int width, int height)
   {
     this.text = s;
     this.SetDimensions(width, height);
     this.GenerateImage();
   }
   public CaptchaText(string s,int width,int height,string familyName)
   {
     this.text = s;
     this.SetDimensions(width, height);
     this.SetFamilyName(familyName);
     this.GenerateImage();
   }
   ~CaptchaText()
   {
     Dispose(false);
   }
   public void Dispose()
   {
     GC.SuppressFinalize(this);
     this.Dispose(true);
   }
   protected virtual void Dispose(bool disposing)
   {
     if (disposing)
     this.image.Dispose();
   }
   private void SetDimensions(int width, int height)
   {
    if (width <= 0)
    throw new ArgumentOutOfRangeException("width",width,"Argument out of range,
                                                                                must be greater than zero.");
    if (height <= 0)
    throw new ArgumentOutOfRangeException("height",height,"Argument out of range,
                                                                                must be greater than zero.");
    this.width = width;
    this.height = height;
   }
   private void SetFamilyName(string familyName)
   {
      try
      {
        Font font = new Font(this.familyName, 12F);
        this.familyName = familyName;
        font.Dispose();
      }
      catch (Exception ex)
      {
        this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
      }
   }
private void GenerateImage()
{
Bitmap bitmap = new Bitmap(this.width,this.height,PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
HatchBrush hatchBrush=new HatchBrush(HatchStyle.SmallConfetti,Color.LightGray,Color.White);
g.FillRectangle(hatchBrush, rect);
   SizeF size;
   float fontSize = rect.Height + 1;
   Font font;
   do
   {
     fontSize--;
     font = new Font(this.familyName, fontSize, FontStyle.Bold);
     size = g.MeasureString(this.text, font);
   } while (size.Width > rect.Width);

  StringFormat format = new StringFormat();
  format.Alignment = StringAlignment.Center;
  format.LineAlignment = StringAlignment.Center;
 GraphicsPath path = new GraphicsPath();
 path.AddString(this.text,font.FontFamily,(int)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);
    hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
    g.FillPath(hatchBrush, path);
    int m = Math.Max(rect.Width, rect.Height);
    for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); 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);
      }
         font.Dispose();
         hatchBrush.Dispose();
         g.Dispose();
         this.image = bitmap;
    }
 } 

Step:2 Create a page named "Captcha.aspx" and add code in Captcha.aspx.cs


protected void Page_Load(object sender, EventArgs e) {   if (Session["CaptchaImageText"] != null)    {       CaptchaText ci = new CaptchaText(this.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook");        this.Response.Clear();        this.Response.ContentType = "image/jpeg";        ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);        ci.Dispose();    }  }


Step:3 Now Call Captcha.aspx in that page you want to appear it for ex: "Default.aspx"

Add code in Default.aspx


<table width="100%">     <tr>       <td align="left">         <img id="imgcaptcha" runat="server" src="~/Captcha.aspx" alt="Enter the code shown" />        </td>     </tr>     <tr>       <td align="left">           <asp:Label runat="server" ID="lblBox" Text="Enter the code shown"></asp:Label>            <br />           <asp:TextBox ID="CodeNumberTextBox" runat="server"></asp:TextBox>           <asp:Label ID="lblerrCaptcha" runat="server" Visible="false"></asp:Label>         </td>      </tr>     <tr>      <td align="left">         <asp:LinkButton ID="lnkGetQuotes" Text="GetQuotes"  runat="server" OnClick="btnGetQuotes_Click">      </td>    </tr> </table>

Now,Compare that to value to what the users had keyed in to your text box, To do that add code in Default.aspx.cs


private Random random = new Random();
 protected void Page_Load(object sender, EventArgs e)
 {
   if (!IsPostBack)
    {
       Session["CaptchaImageText"] = "";
       Session["CaptchaImageText"] = GenerateRandomCode();
    }
 }
private string GenerateRandomCode()
{
            string s = "";
            for (int i = 0; i < 6; i++)
                s = String.Concat(s, this.random.Next(10).ToString());
            return s;
}
protected void btnGetQuotes_Click(object sender, EventArgs e)
{
   if (Convert.ToString(Session["CaptchaImageText"]) != "" &&
             Convert.ToString(CodeNumberTextBox.Text) != "")
   {
     if (CodeNumberTextBox.Text == Session["CaptchaImageText"].ToString())
     { 
        // add your code for the button
     }
    else
     {
         lblerrCaptcha.Visible = true;
         lblerrCaptcha.Text = "Please enter the correct code";
     }
}
else
   {
          lblerrCaptcha.Visible = true;
          lblerrCaptcha.Text = "Please enter the code"; 
   }
} 

The output is like as:


Thats it, Congratulations you have created your Captcha Image in your website.

8 comments:

  1. Liked it,,,,,,,, Useful
    Techterabyte.blogspot.com

    ReplyDelete
  2. This is my first visit to your blog, your post made productive reading, thank you. dot net training in chennai

    ReplyDelete
    Replies
    1. Hi All ,
      I am trying to implement it in my already existing cide but failing . I cant understand the linking of the pages . The eroor I get is
      Compiler Error Message: ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl).

      Delete
  3. You post explain everything in detail and it was very interesting to read. Thank you. nata coaching centres in chennai

    ReplyDelete
  4. Informative article, just what I was looking for.seo services chennai

    ReplyDelete