在 Web 系統中,驗證碼(CAPTCHA)常用於註冊、登入等場景以提升安全性。本文將詳細示範如何使用 ASP.NET 產生包含雜訊背景的驗證碼圖片,並提供完整程式碼範例。
System.Drawing 將字串繪製成圖片,並加入干擾背景提高辨識難度。建立 generateVCode 函式,依指定長度產生字串:
''' <summary>
''' 產生隨機字串(數字+大寫字母)供驗證碼使用
''' </summary>
Private Function generateVCode(ByVal CodeLength As Integer) As String
Dim VCode As String = String.Empty
Dim randObj As New Random()
Dim c As Integer = 63
For i As Byte = 1 To CodeLength
c = randObj.Next(35) ' 0-34
If c >= 10 Then c += 7 ' 跳過 ':' 到 '@' 之間的符號
c += 48 ' 轉為 ASCII '0'-'9', 'A'-'Z'
VCode &=amp; Chr(c)
Next
Return VCode
End Function
為了增加圖片複雜度,隨機選取 HatchBrush 樣式:
''' <summary>
''' 產生隨機筆刷樣式(用於圖片背景)
''' </summary>
Private Function generateHatchStyle() As HatchStyle
Dim slist As New ArrayList()
For Each style As HatchStyle In System.Enum.GetValues(GetType(HatchStyle))
slist.Add(style)
Next
Dim randObj As New Random()
Dim index As Integer = randObj.Next(slist.Count)
Return CType(slist(index), HatchStyle)
End Function
GenerateVCodeImage 函式整合上述邏輯,並將驗證碼文字寫入圖片:
''' <summary>
''' 產生驗證碼圖片並輸出至 Response
''' </summary>
Private Function GenerateVCodeImage() As String
Dim oBitmap As New Bitmap(90, 35)
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
Dim sText As String = generateVCode(5) ' 取得 5 碼驗證碼
Dim sFont As String = "Comic Sans MS"
Dim foreColor As Color = Color.FromArgb(220, 220, 220)
Dim backColor As Color = Color.FromArgb(190, 190, 190)
' 背景筆刷
Dim oBrush As New HatchBrush(generateHatchStyle(), foreColor, backColor)
' 文字筆刷
Dim oBrushWrite As New SolidBrush(Color.Gray)
oGraphic.FillRectangle(oBrush, 0, 0, 100, 50)
oGraphic.TextRenderingHint = TextRenderingHint.AntiAlias
Dim oFont As New Font(sFont, 14)
Dim oPoint As New PointF(5.0F, 4.0F)
oGraphic.DrawString(sText, oFont, oBrushWrite, oPoint)
Response.ContentType = "image/jpeg"
oBitmap.Save(Response.OutputStream, ImageFormat.Jpeg)
oBitmap.Dispose()
Return sText ' 回傳驗證碼供 Session 驗證使用
End Function
在 VCode.aspx 的 Page_Load 中呼叫 GenerateVCodeImage(),並將回傳字串存入 Session["VCode"]。前端頁面即可用 <img src="VCode.aspx" /> 顯示驗證碼圖片,提交時比對 Session 即可驗證。