• home
  • forum
  • my
  • kt
  • download
  • Creating CAPTCHA images with Visual Basic (VB)

    Author: 2008-09-16 08:37:43 From:

    CAPTCHA remains the most popular method of physical verification which cannot be beaten by a machine or a program yet. This article presents a simple way of creating CAPTCHA images using Visual Basic

    What Is CAPTCHA? CAPTCHA is an abbreviation for Completely Automated Public Turing test to tell Computers and Humans Apart. It involves images of words or numbers that cannot be read by OCR (Object Character Recognition) programs and can be may be easily read by humans.

    The following code can be used as a simple way to create CAPTCHA images in Visual Basic

     

    Public Function GenerateNewCaptcha(ByVal path As String, ByVal height As Integer, ByVal width As Integer) As String

    Dim r As New Random 'to generate a random angle
    Dim salt As String = CreateSalt(4) 'generates a random string
    Dim bmp As New Bitmap(width, height, PixelFormat.Format24bppRgb) 'creates ‘a 24bit bitmap in memory
    Dim g As Graphics = Graphics.FromImage(bmp)
    g.TextRenderingHint = TextRenderingHint.AntiAlias 'this will smoothen the Font
    g.Clear(Color.Black) 'this clears the background and paints specified color
    g.DrawRectangle(Pens.White, 1, 1, width - 3, height - 3)
    g.DrawRectangle(Pens.Black, 0, 0, width, height)
    Dim mymat As New System.Drawing.Drawing2D.Matrix 'matrix used for ‘rotation transformation
    Dim i As Integer
    For i = 0 To Len(salt) - 1 'we will rotate each literal at a specified angle
    mymat.Reset()    ' matrix should be initialized to identity matrix
    mymat.RotateAt(r.Next(-30, 0), New PointF(width * (0.12 * i), height *_  0.5)) 'rotate at any angle b/w -30 and 0
    g.Transform = mymat 'apply the transform
    g.DrawString(salt.Chars(i), New Font("Comic Sans MS", 10, _ FontStyle.Italic),
    SystemBrushes.ActiveCaptionText, width * (0.12 * i), height * 0.5) 'draw ‘the text on our image
    g.ResetTransform()
    Next
    bmp.Save(path, ImageFormat.Gif) 'save the gif at specified path and name
    g.Dispose() 'clean up
    bmp.Dispose() 'ok the mess is over
    Return salt 'return the string painted for verification

    End Function

    This function creates a random Gif file of provided width and height the string on the gif file is rotated randomly and returns the random string for being painted. It creates the CAPTCHA image and stores it in the provided path to be used later. For verification of the string I have stored the string as a session variable even though hidden label could have been used.
    The various function for drawing and image creation and transformation are provided in System.Drawing.Imaging and the various fonts are provided in System.Drawing.Text.

    For simplicity I have used a single font but different font can be used by using an array of type fonts.

    Next is the definition of the function Createsalt()

     

    Public Function CreateSalt(ByVal size As Integer) As String

    Dim rng As New RNGCryptoServiceProvider
    Dim buff(size) As Byte
    rng.GetBytes(buff)
    ' Return a Base64 string representation of the random number
    Return Convert.ToBase64String(buff)

    End Function

    This function generates a cryptographic random number using the cryptographic classes defined in the .NET Framework. The various cryptographic classes are defined in the System.Security.Cryptography namespace.

    Now go on and create a class by the name of CAPTCHAclass and define these two functions inside it.

    Now let us implement this class on an aspx page.

    Drop an image box, label, textbox and a button from the toolbox to an aspx page. Use the following specifications:

     image box: ‘id=image height=100, width=200
     button: id=btnRegister
     textbox: id=textbox1
     label: id=lblMessage

     

    Now create the following procedures or more commonly called sub in the page class:

     

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Handles MyBase.Load

    If Not Page.IsPostBack Then 
    Dim verify As New Verification
    Dim salt As String = _ Verify.CreateImage(Server.MapPath(".\Random.gif"), 100, _
    200)    'I have created a file named Random.gif in the same directory as ‘my web page size 100,200
    Image.ImageUrl = Server.MapPath(".\Random.gif")
    Session.Add("salt", salt)    'Add our salt to session for verification so that ‘we can check on postback
    Dim params As System.Collections.Specialized.NameValueCollection
    params = Request.QueryString()
    If params.Count > 0 Then lblMessage.Text = params.Item("reason")
    End If

    End Sub

     

    Private Sub btnRegister_Click(ByVal sender As System.Object, ByVal e As System.
    EventArgs) Handles btnRegister.Click

    If Not TextBox1.Text.Equals(Session.Item("salt")) Then
    Response.Redirect(Request.Url.ToString & "?reason=The Strings did not_ match")    'if we donot do it page will be considered a postback
    Else
    lblMessage.text=”Good Boy”
    End If

    End Sub


    If you wish to make any changes to this code, especially in case of creating the image, keep in mind size of proportion between size of your image box and size of image you are creating. This affects your image’s clarity and also font may go out of bounds.

    Also you can make your image look more appealing by filling your recantgle with different styles and brushes.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      .NET (9)
      Buttons (3)
      Database Related (9)
      Date and Time (4)
      Development (4)
      Error Handling (3)
      File Manipulation (6)
      Introduction to Visual Basic (24)
      Miscellaneous (3)
      Multimedia (10)
      Networking (10)
      Security (1)
      VB Script (6)

    New

    Hot