How To Generate Captcha Image In Asp.net 2.0

  • why Captcha Image Required ?

          Restrict User to Auto Registration or Login in the site. General Senario for that if you have a company who create new login or registration for the users. in this situation you never be going registration or login one by one. you create simple file in that file you put that information and one program which execute this process. as a company you want to restict this kind of activity at that time you want some code which is dyanamically generate and user enter that code and done the login or registration process at that time you can use this Captcha Image.

 

Steps :

1) create simple Asp.net 2.0 Application.

2) Add New Page (GenerateImage.aspx) — Generate Random Image and display in to page

put below code in to the web page.

2.1) create property (Height – Image Height,Width – Image Width,text – Display Text)

2.2) create Random No

private Random ObjRandom = new Random();

here below all code for (GenerateImage.aspx.cs)

   1: private int _height = 75;
   2:    public int height
   3:    {
   4:        get { return _height; }
   5:        set { _height = value; }
   6:    }
   7:  
   8:    private string _text = "generateimage";
   9:    public string text
  10:    {
  11:        get { return _text; }
  12:        set { _text = value; }
  13:    }
  14:  
  15:    private int _width = 275;
  16:    public int width
  17:    {
  18:        get { return _width; }
  19:        set { _width = value; }
  20:    }
  21:    /// <summary>
  22:    /// Get Character from Random Number
  23:    /// </summary>
  24:    /// <param name="genNo"></param>
  25:    /// <returns></returns>
  26:    public string getChar(int genNo)
  27:    {
  28:        switch (genNo)
  29:        { 
  30:            case 0:
  31:                return "a";
  32:            case 1:
  33:                return "b";
  34:            case 2:
  35:                return "c";
  36:            case 3:
  37:                return "d";
  38:            case 4:
  39:                return "e";
  40:            case 5:
  41:                return "f";
  42:            case 6:
  43:                return "g";
  44:            case 7:
  45:                return "h";
  46:            case 8:
  47:                return "i";
  48:            case 9:
  49:                return "j";
  50:        }
  51:        return string.Empty;
  52:    }
  53:  
  54:    //generating random numbers.
  55:    private Random ObjRandom = new Random();
  56:  
  57:    protected void Page_Load(object sender, EventArgs e)
  58:    {
  59:        //generate random text
  60:        Random r = new Random();
  61:        string str =r.Next().ToString().Substring(0,4);
  62:        char[] ch = str.ToCharArray();
  63:        text = string.Empty;
  64:        foreach (char var in ch)
  65:        {
  66:            //get appropriate char
  67:            text += getChar(Convert.ToInt32(var.ToString()));
  68:        }
  69:        //generate random image
  70:        GenerateImage();
  71:    }
  72:    /// <summary>
  73:    /// Generate Image
  74:    /// </summary>
  75:    private void GenerateImage()
  76:    {
  77:        //using System.Drawing; and using System.Drawing.Imaging;
  78:        //Create a new 32-bit bitmap image.
  79:        //specify height width
  80:        //if you want to change pass that value in to query string
  81:        Bitmap ObjBitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
  82:        //Create a graphics object 
  83:        Graphics ObjGraphic = Graphics.FromImage(ObjBitmap);
  84:        ObjGraphic.SmoothingMode = SmoothingMode.HighQuality;
  85:  
  86:        Rectangle ObjRect = new Rectangle(0, 0, this.width, this.height);
  87:  
  88:        // Fill in the background color
  89:        //using System.Drawing.Drawing2D;
  90:        //you specify different fillup style
  91:        HatchBrush ObjHatchBrush = new HatchBrush(HatchStyle.BackwardDiagonal, Color.Transparent, Color.Transparent);
  92:        ObjGraphic.FillRectangle(ObjHatchBrush, ObjRect);
  93:        // Text Font Size
  94:        SizeF ObjectFontSize;
  95:        float fontSize = ObjRect.Height + 3;
  96:        Font ObjFont;
  97:        // Adjust the font size until the text fits within the image.
  98:        do
  99:        {
 100:            fontSize--;
 101:            ObjFont = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Bold);
 102:            ObjectFontSize = ObjGraphic.MeasureString(this.text, ObjFont);
 103:        } while (ObjectFontSize.Width > ObjRect.Width);
 104:  
 105:        // Set up the text format.
 106:        StringFormat ObjectStringFormat = new StringFormat();
 107:        ObjectStringFormat.Alignment = StringAlignment.Center;
 108:        ObjectStringFormat.LineAlignment = StringAlignment.Center;
 109:  
 110:        // Create a path using the text and warp it randomly.
 111:        GraphicsPath ObjGraphicPath = new GraphicsPath();
 112:        ObjGraphicPath.AddString(this.text, ObjFont.FontFamily, (int)ObjFont.Style, ObjFont.Size, ObjRect, ObjectStringFormat);
 113:        float size = 6F;
 114:        PointF[] points =
 115:            {
 116:                new PointF(this.ObjRandom.Next(ObjRect.Width) / size, this.ObjRandom.Next(ObjRect.Height) / size),
 117:                new PointF(ObjRect.Width - this.ObjRandom.Next(ObjRect.Width) / size, this.ObjRandom.Next(ObjRect.Height) / size),
 118:                new PointF(this.ObjRandom.Next(ObjRect.Width) / size, ObjRect.Height - this.ObjRandom.Next(ObjRect.Height) / size),
 119:                new PointF(ObjRect.Width - this.ObjRandom.Next(ObjRect.Width) / size, ObjRect.Height - this.ObjRandom.Next(ObjRect.Height) / size)
 120:            };
 121:        Matrix ObjMatrix = new Matrix();
 122:        ObjMatrix.Translate(0F, 0F);
 123:        ObjGraphicPath.Warp(points, ObjRect, ObjMatrix, WarpMode.Perspective, 0F);
 124:  
 125:        //Draw Text
 126:        ObjHatchBrush = new HatchBrush(HatchStyle.Wave, Color.Gray, Color.DarkGray);
 127:        ObjGraphic.FillPath(ObjHatchBrush, ObjGraphicPath);
 128:  
 129:        //Add more noise in the image
 130:        int m = Math.Max(ObjRect.Width, ObjRect.Height);
 131:        for (int i = 0; i < (int)(ObjRect.Width * ObjRect.Height / 30F); i++)
 132:        {
 133:            int x = this.ObjRandom.Next(ObjRect.Width);
 134:            int y = this.ObjRandom.Next(ObjRect.Height);
 135:            int w = this.ObjRandom.Next(m / 52);
 136:            int h = this.ObjRandom.Next(m / 52);
 137:            ObjGraphic.FillEllipse(ObjHatchBrush, x, y, w, h);
 138:        }
 139:        ObjFont.Dispose();
 140:        ObjHatchBrush.Dispose();
 141:        ObjGraphic.Dispose();
 142:        this.Response.ContentType = "image/jpeg";
 143:        Session.Add("ImageString",this.text);
 144:        ObjBitmap.Save(this.Response.OutputStream, ImageFormat.Jpeg);
 145:    }

 3) Now In Default.aspx

<table>

<tr>

<td>

Enter User Name :</td>

<td>

<asp:TextBox ID=”txtUserName” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator3″ runat=”server” ControlToValidate=”txtUserName”

ErrorMessage=”RequiredFieldValidator”>*</asp:RequiredFieldValidator></td>

</tr>

<tr>

<td>

Enter Email Address :</td>

<td>

<asp:TextBox ID=”txtEmailAddress” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ runat=”server” ControlToValidate=”txtEmailAddress”

ErrorMessage=”RequiredFieldValidator”>*</asp:RequiredFieldValidator></td>

</tr>

<tr>

<td>

Description :</td>

<td>

<asp:TextBox ID=”txtDescrition” TextMode=”MultiLine” runat=”server”></asp:TextBox>

</td>

</tr>

<tr>

<td>

Type Below Code :

</td>

<td>

<asp:TextBox ID=”txtImage” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ControlToValidate=”txtImage”

ErrorMessage=”RequiredFieldValidator”>*</asp:RequiredFieldValidator></td>

</tr>

<tr>

<td align=”center” colspan=”2″>

<!– Get Image From the GenerateImage Page –>

<img id=”img” src=”GenerateImage.aspx” />

</td>

</tr>

<tr>

<td colspan=”2″ align=”center”>

<asp:Button ID=”btnSubmit” Text=”Submit” runat=”server” OnClick=”btnSubmit_Click” />

<asp:Button ID=”btnCancel” Text=”Cancel” runat=”server” OnClick=”btnCancel_Click” ValidationGroup=”Cancel” />

</td>

</tr>

</table>

4) Now In Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

}

protected void btnSubmit_Click(object sender, EventArgs e)

{

string str = Session[“ImageString”].ToString();

if (str == txtImage.Text)

{

Response.Write(“you enter right”);

}

else

{

Response.Write(“you enter false”);

}

}

protected void btnCancel_Click(object sender, EventArgs e)

{

Response.Redirect(“default.aspx”);

}

 

Thnx.

Advertisements

3 comments

  1. binajar · · Reply

    Veryyy Good Code.. I manage to change the code to vb.net thanks Patriwala

  2. i copy this code in my project but it gives following errors, how to fix them, plz can u help me
    Error 4 The name ‘ImageFormat’ does not exist in the current context
    Error 3 The name ‘PixelFormat’ does not exist in the current context
    Error 2 ‘GenerateImage’: member names cannot be the same as their enclosing type

    1. bebins · · Reply

      using System.Drawing;
      using System.Drawing.Drawing2D;
      using System.Drawing.Imaging;
      using System.Web.SessionState;

      dont 4get to use these namespace mentioned above…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s