Wednesday, September 12, 2007

Visual Confirmation Code

Import the Following Namespaces

System.Data
System.Drawing
System.IO
System.Text
System.Security.Cryptography

########################
###The Code Goes here
########################
Dim strVisualString As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not IsPostBack = True Then
GenerateVisualConfirmationCode()
End If
End Sub
Sub GenerateVisualConfirmationCode()
Dim str As String = Server.MapPath("../images/VisualConfirmation/test1.jpg")
Dim str2 As String = Server.MapPath("../images/VisualConfirmation/test3.jpg")
If System.IO.File.Exists(str2) Then
System.IO.File.Delete(str2)
End If
Dim b As New System.Drawing.Bitmap(str)
Dim f As New Font("Arial", 30)
Dim graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(b)
Dim width As Integer = CInt(graphics.MeasureString("ABCDEFGH", f).Width)
Dim height As Integer = CInt(graphics.MeasureString("ABCDEFGH", f).Height)
b = New Bitmap(b, New Size(200, 50))
graphics = System.Drawing.Graphics.FromImage(b)
'graphics.Clear(Color.DarkBlue)
graphics.Clear(Color.White)
strVisualString = RandomString(6)
graphics.DrawString(strVisualString, f, New SolidBrush(Color.Black), 0, 0)
graphics.Flush()
b.Save(str2, System.Drawing.Imaging.ImageFormat.Jpeg)
End Sub
Function RandomString(ByVal iLength As Integer) As String
Dim iZero, iNine, iA, iZ, iCount, iRandNum As Integer
Dim sRandomString As String
Dim rRandom As New Random(System.DateTime.Now.Millisecond)
iZero = Asc("0")
iNine = Asc("9")
iA = Asc("A")
iZ = Asc("Z")
sRandomString = ""
While (iCount < iLength)
iRandNum = rRandom.Next(iZero, iZ)
If ((iRandNum >= iZero) And (iRandNum <= iNine) Or (iRandNum >= iA) And (iRandNum <= iZ)) Then
sRandomString = sRandomString + Chr(iRandNum)
iCount = iCount + 1
End If
End While
RandomString = sRandomString
End Function