在登入時或從網頁寄Mail時常要用到驗證碼,利用驗證碼防止機器人攻擊. 所謂驗證碼,就是將一串隨機產生的數字、符號、文字等,變成一個圖案。
Dim chkCode As String = String.Empty
'顏色列表,用於驗證碼、噪線、噪點
Dim color As Color() = {Drawing.Color.Navy, Drawing.Color.Black, Drawing.Color.Red, Drawing.Color.Blue, Drawing.Color.Green, Drawing.Color.Orange, Drawing.Color.Brown, Drawing.Color.Brown, Drawing.Color.DarkBlue}
'字體列表,用於驗證碼
Dim font As String() = {"Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact"}
'驗證碼的字元集,去掉了一些容易混淆的字元
Dim character As Char() = {"2"c, "3"c, "4"c, "5"c, "6"c, "8"c, _
"9"c, "A"c, "B"c, "C"c, "D"c, "E"c, _
"F"c, "G"c, "H"c, "J"c, "K"c, "L"c, _
"M"c, "N"c, "P"c, "R"c, "S"c, "T"c, _
"W"c, "X"c, "Y"c}
Dim rnd As New Random()
For i As Integer = 0 To 3
'生成驗證碼字串
chkCode += character(rnd.[Next](character.Length))
Next
Dim bmp As New Bitmap(100, 40)
Dim g As Graphics = Graphics.FromImage(bmp)
g.Clear(Drawing.Color.White)
For i As Integer = 0 To 9
'畫噪線
Dim x1 As Integer = rnd.[Next](100)
Dim y1 As Integer = rnd.[Next](40)
Dim x2 As Integer = rnd.[Next](100)
Dim y2 As Integer = rnd.[Next](40)
Dim clr As Color = color(rnd.[Next](color.Length))
g.DrawLine(New Pen(clr), x1, y1, x2, y2)
Next
For i As Integer = 0 To chkCode.Length - 1
'畫驗證碼字串
Dim fnt As String = font(rnd.[Next](font.Length))
Dim ft As New Font(fnt, 18)
Dim clr As Color = color(rnd.[Next](color.Length))
g.DrawString(chkCode(i).ToString(), ft, New SolidBrush(clr), CSng(i) * 20 + 8, CSng(8))
Next
For i As Integer = 0 To 99
'畫噪點
Dim x As Integer = rnd.[Next](bmp.Width)
Dim y As Integer = rnd.[Next](bmp.Height)
Dim clr As Color = color(rnd.[Next](color.Length))
bmp.SetPixel(x, y, clr)
Next
'清除該頁輸出緩存,設置該頁無緩存
Response.Buffer = True
Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0)
Response.Expires = 0
Response.CacheControl = "no-cache"
Response.AppendHeader("Pragma", "No-Cache")
'將驗證碼圖片寫入記憶體流,並將其以 "image/Png" 格式輸出
Dim ms As New MemoryStream()
Try
bmp.Save(ms, ImageFormat.Png)
Response.ClearContent()
Response.ContentType = "image/Png"
Response.BinaryWrite(ms.ToArray()) '顯示圖形顯證碼
Finally
'顯式釋放資源
bmp.Dispose()
g.Dispose()
End Try