首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 實作驗證碼圖片產生完整教學

     編輯:關於ASP.NET

在 Web 系統中,驗證碼(CAPTCHA)常用於註冊、登入等場景以提升安全性。本文將詳細示範如何使用 ASP.NET 產生包含雜訊背景的驗證碼圖片,並提供完整程式碼範例。

核心流程

  1. 產生隨機驗證碼字串(含數字與大寫字母)。
  2. 利用 System.Drawing 將字串繪製成圖片,並加入干擾背景提高辨識難度。
  3. 將圖片以 JPEG 格式輸出至回應串流。

步驟 1:產生隨機驗證碼字串

建立 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

步驟 2:產生隨機背景筆刷樣式

為了增加圖片複雜度,隨機選取 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

步驟 3:繪製並輸出驗證碼圖片

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 即可驗證。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved