Results 1 to 9 of 9

Thread: Captcha in VB.NET

  1. #1

    Default Captcha in VB.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 VB.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:
            Dim strPathToImage As String = "captchaimg/captcha.gif" ' Make sure the directory is writable by your web server!
            Dim strText As String = fncDrawCaptcha(Server.MapPath(strPathToImage)) 
            imgCaptcha.ImageUrl = strPathToImage
            Session.Add("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:
    Function fncDrawCaptcha(ByVal path As String) As String 
    
        '*** Editable Values
        Dim BackgroundColor As [String]() = New [String]() {255, 255, 255} ' The 3 numbers represent in order RED, GREEN, BLUE for the captcha's background color
        Dim RandomBackgroundNoiseColor As Boolean = True ' True / False. If you choose True, BackgroundNoiseColor will not apply 
        Dim RandomTextColor As Boolean = True ' True / False. If you choose True, TextColor will not apply 
        Dim BackgroundNoiseColor As [String]() = New [String]() {150, 150, 150} ' The 3 numbers represent in order RED, GREEN, BLUE
        Dim TextColor As [String]() = New [String]() {200, 200, 200} ' The 3 numbers represent in order RED, GREEN, BLUE
        Dim BackgroundNoiseTexture As HatchStyle = 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
        Dim length as integer = 6 ' Number of characters to generate
        '*** END Editable Values
        
        Dim height as integer = 100
        Dim width as integer = 200
        width = width + ((length - 6) * 30)
        Dim ranRotate As New Random
        Dim strText As String = left(replace(System.Guid.NewGuid().ToString(), "-", ""), length)
        Dim bmpCanvas As New Bitmap(width, height, PixelFormat.Format24bppRgb)
        Dim graCanvas As Graphics = Graphics.FromImage(bmpCanvas)
        Dim recF As New RectangleF(0, 0, width, height)
        Dim bruBackground As Brush
        Dim letterBrush as SolidBrush
    
        graCanvas.TextRenderingHint = TextRenderingHint.AntiAlias 
    
        If RandomBackgroundNoiseColor = true Then
            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)))
        End If
        
        graCanvas.FillRectangle(bruBackground, recF)
    
        If RandomTextColor = true Then
            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))) 
        End If
        
        Dim matRotate As New System.Drawing.Drawing2D.Matrix 
        Dim i As Integer
        For i = 0 To Len(strText) - 1 
            matRotate.Reset()    
            matRotate.RotateAt(ranRotate.Next(-30, 30), New PointF(width/(Len(strText) + 1) * i, height *  0.5)) 
            graCanvas.Transform = matRotate
            If i = 0 Then
                graCanvas.DrawString(strText.Chars(i), New Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width/(Len(strText) + 1) * i, height * 0.4) 'draw ‘the text on our image
            ElseIf i = 1 Then
                graCanvas.DrawString(strText.Chars(i), New Font("Arial", 30, FontStyle.Bold), letterBrush, width/(Len(strText) + 1) * i, height * 0.1) 'draw ‘the text on our image
            ElseIf i = 2 Then
                graCanvas.DrawString(strText.Chars(i), New Font("Times New Roman", 25, FontStyle.Italic), letterBrush, width/(Len(strText) + 1) * i, height * 0.5) 'draw ‘the text on our image
            ElseIf i = 3 Then
                graCanvas.DrawString(strText.Chars(i), New Font("Georgia", 35, FontStyle.Bold), letterBrush, width/(Len(strText) + 1) * i, height * 0.1) 'draw ‘the text on our image
            ElseIf i = 4 Then
                graCanvas.DrawString(strText.Chars(i), New Font("Verdana", 25, FontStyle.Italic), letterBrush, width/(Len(strText) + 1) * i, height * 0.5) 'draw ‘the text on our image
            ElseIf i = 5 Then
                graCanvas.DrawString(strText.Chars(i), New Font("Geneva", 30, FontStyle.Bold), letterBrush, width/(Len(strText) + 1) * i, height * 0.1) 'draw ‘the text on our image
            Else
                graCanvas.DrawString(strText.Chars(i), New Font("Arial", 30, FontStyle.Italic), letterBrush, width/Len(strText) * i, height * 0.5) 'draw ‘the text on our image
            End If
            graCanvas.ResetTransform()
        Next
    
        bmpCanvas.Save(path, ImageFormat.Gif) 
        graCanvas.Dispose()
        bmpCanvas.Dispose()
            
        Return strText
    
    End Function 
    
    Sub subCheckCaptcha(sender As Object, e As System.EventArgs)
    
        If Not txtCaptcha.Text = Session.Item("strText") Then
            lblMessage.text = "The characters does not match"
        Else
            lblMessage.text = ""
            subSubmitForm()
        End If
            
    End Sub
    
    Sub subSubmitForm()
        'Your code in here
        response.write("Captcha text entered successfully")
    End Sub
    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 Attached Files
    CWA - CoolWebAwards.com

  2. #2

    Default

    Does Captcha on every website is made by VB.Net?

  3. #3

    Default

    The code Project and added accessible sources accept a amount of cipher snippets for bearing a captcha image on a web page. However, the majority are old and use moderately circuitous JavaScript and/or C#.

  4. #4

    Default

    Very nice quote.. im understood the concept of captcha.thanks.

  5. #5
    Sapphire Star member
    Join Date
    Aug 2011
    Posts
    70

    Default

    Thanks for such an awesome information.. Really appreciate it!

  6. #6

    Default

    Project could increase the availability of sources and accept the number of bits and pieces of encryption with the captcha image on a web page. However, most of the old and the moderate use of JavaScript, tortuous and / or C #.

  7. #7
    Prospect
    Join Date
    Sep 2011
    Location
    Naples,US
    Posts
    5

    Thumbs up Informative..

    I have found you shared post so informative. Thanks for sharing your concept about Captcha.

  8. #8
    Prospect
    Join Date
    Oct 2012
    Location
    India
    Posts
    1

    Default

    thank you for the example. it helps alot

  9. #9

    Default help please

    Hi, I am a junior programmer.
    Thanks for the CODE. Does anyone can tell how i should do the option to regenerate the image?? I mean, In my application i have an aditional option so User can click it to re generate the image to get an easier image to read. Thanks for your help =)

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
  •