+ Reply to Thread
Results 1 to 1 of 1

Thread: Captcha in C#.NET

  1. #1

    Captcha in C#.NET

    This tutorial will show you how to setup a Captcha ("Completely Automated Public Turing test to tell Computers and Humans Apart") for your website’s signup or email forms, or for whatever purpose using C#.NET. Simply follow the instructions below and you’ll have a professional looking captcha setup in only a few minutes. The complete code can be downloaded here, or you can simply copy and paste the code below. The Captcha is entirely customizable from all colors, background noise, and number of characters to display. Click here for an example of the Captcha using random colors with a striped background noise.

    First off, as the characters are written on an image, we need to import the following Namespaces:

    Code:
    <%@ import Namespace="System.Drawing.Imaging" %>
    <%@ import Namespace="System.Drawing" %>
    <%@ import Namespace="System.Drawing.Drawing2D" %>
    <%@ import Namespace="System.Drawing.Text" %>
    Next, the following lines needs to go into the “If Not IsPostback” section of your Page_Load Subroutine to generate the Captcha’s image the first time the page loads. You need to allow write access for your web server (Usually IWPD user in IIS) to the directory mentioned (“/captchaimg”). This allows an image file with the captcha characters on to be written to this folder to display to the user.

    Code:
            string strPathToImage = "captchaimg/captcha.gif";// Make sure the directory is writable by your web server!
            string strText = fncDrawCaptcha(Server.MapPath(strPathToImage));
            imgCaptcha.ImageUrl = strPathToImage;
            Session["strText"] = strText;
    Now, copy the functions and subroutines below into your VB code. In the function (fncDrawCaptcha) you’ll see lines marked “Editable Values”. These values can be edited to personalize how your Captcha image will look like:

    BackgroundColor, BackgroundNoiseColor and TextColor - The values (255, 255, 255) represent the RGB (Red, Green, Blue) value for each part of the Captcha image.
    RandomBackgroundNoiseColor and RandomTextColor - If the values are set to True, the BackgroundNoiseColor and TextColor values mentioned above will be ignored and random colors will be used.
    BackgroundNoiseTexture - As with all Captcha’s, you need a background distortion to make it difficult for programs to decipher the text. There are a lot of options to choose from (see the code).
    length – The number of characters to display on the Captcha image.

    Your code for when the form is submitted should go in the “subSubmitForm” as indicated.

    Code:
    public string fncDrawCaptcha(string path)
    {
        
        //*** Editable Values
        int[] BackgroundColor = new int[] { 255, 255, 255 };// The 3 numbers represent in order RED, GREEN, BLUE for the captcha's background color
        bool RandomBackgroundNoiseColor = true;// True / False. If you choose True, BackgroundNoiseColor will not apply 
        bool RandomTextColor = true;// True / False. If you choose True, TextColor will not apply 
        int[] BackgroundNoiseColor = new int[] { 150, 150, 150 };// The 3 numbers represent in order RED, GREEN, BLUE
        int[] TextColor = new int[] { 200, 200, 200 };// The 3 numbers represent in order RED, GREEN, BLUE
        HatchStyle BackgroundNoiseTexture = HatchStyle.Min;// replace ".Min" with any of the following: Horizontal, Vertical, ForwardDiagonal, BackwardDiagonal, Cross, DiagonalCross, Percent05, Percent10, Percent20, Percent25, Percent30, Percent40, Percent50, Percent60, Percent70, Percent75, Percent80, Percent90, LightDownwardDiagonal, LightUpwardDiagonal, DarkDownwardDiagonal, DarkUpwardDiagonal, WideDownwardDiagonal, WideUpwardDiagonal, LightVertical, LightHorizontal, NarrowVertical, NarrowHorizontal, DarkVertical, DarkHorizontal, DashedDownwardDiagonal, DashedUpwardDiagonal, DashedHorizontal, DashedVertical, SmallConfetti, LargeConfetti, ZigZag, Wave, DiagonalBrick, HorizontalBrick, Weave, Plaid, Divot, DottedGrid, DottedDiamond, Shingle, Trellis, Sphere, SmallGrid, SmallCheckerBoard, LargeCheckerBoard, OutlinedDiamond, SolidDiamond, LargeGrid, Min, Max
        int length = 6;// Number of characters to generate
        //*** END Editable Values
        
        int height = 100;
        int width = 200;
        width = width + ((length - 6) * 30);
        Random ranRotate = new Random();
        
        string strText = System.Guid.NewGuid().ToString();
        strText = strText.Replace("-", String.Empty);
        strText = strText.Substring(0, length);
        
        Bitmap bmpCanvas = new Bitmap(width, height, PixelFormat.Format24bppRgb);
        Graphics graCanvas = Graphics.FromImage(bmpCanvas);
        RectangleF recF = new RectangleF(0, 0, width, height);
        Brush bruBackground = default(Brush);
        SolidBrush letterBrush = default(SolidBrush);
        
        graCanvas.TextRenderingHint = TextRenderingHint.AntiAlias;
        
        if (RandomBackgroundNoiseColor == true) {
            bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))), Color.FromArgb(BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]));
        }
        else {
            bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb(BackgroundNoiseColor[0], BackgroundNoiseColor[1], BackgroundNoiseColor[2]), Color.FromArgb(BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]));
        }
        
        graCanvas.FillRectangle(bruBackground, recF);
        
        if (RandomTextColor == true) {
            letterBrush = new SolidBrush(Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))));
        }
        else {
            letterBrush = new SolidBrush(Color.FromArgb(TextColor[0], TextColor[1], TextColor[2]));
        }
        
        System.Drawing.Drawing2D.Matrix matRotate = new System.Drawing.Drawing2D.Matrix();
        int i = 0;
        for (i = 0; i <= strText.Length - 1; i++) {
            matRotate.Reset();
            int intChars = strText.Length;
            int x = width / (intChars + 1) * i;
            int y = height / 2;
            //matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(width / (intChars + 1) * i, height * 0.5) );
            matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(x, y) );
            graCanvas.Transform = matRotate;
            if (i == 0) {
                    //draw ‘the text on our image
                //graCanvas.DrawString(strText.Chars(i), new Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, height * 0.4);
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
            }
            else if (i == 1) {
                    //draw ‘the text on our image
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Arial", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
            }
            else if (i == 2) {
                    //draw ‘the text on our image
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Times New Roman", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
            }
            else if (i == 3) {
                    //draw ‘the text on our image
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Georgia", 35, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
            }
            else if (i == 4) {
                    //draw ‘the text on our image
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
            }
            else if (i == 5) {
                    //draw ‘the text on our image
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Geneva", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
            }
            else {
                    //draw ‘the text on our image
                graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
            }
            graCanvas.ResetTransform();
        }
        
        bmpCanvas.Save(path, ImageFormat.Gif);
        graCanvas.Dispose();
        bmpCanvas.Dispose();
            
        return strText;
    }
    
    public void subCheckCaptcha(object sender, System.EventArgs e)
    {
        
        if (!(txtCaptcha.Text == Session["strText"].ToString())) {
            lblMessage.Text = "The characters does not match";
        }
        else {
            lblMessage.Text = "";
            subSubmitForm();
            
        }
    }
    
    public void subSubmitForm()
    {
        //Your code in here
        Response.Write("Captcha text entered successfully");
    }
    Use the following controls in your form section to display the Captcha to your website users

    Code:
      <p>
        <asp:Image ID="imgCaptcha" runat="server" />
      </p>
      <p>
        <asp:TextBox ID="txtCaptcha" runat="server" />
      </p>
      <p>
        <asp:Label ID="lblMessage" runat="server" CssClass="red" />
      </p>
      <p>
        <asp:Button ID="btnSubmit" runat="server" OnClick="subCheckCaptcha" Text="Submit" />
      </p>
    Enjoy!

    * This code is provided for free. If you like or use it, a link to this post would be appreciated (but you are under no obligation to do so).
    Attached Files
    CWA - CoolWebAwards.com

+ Reply to Thread

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts