提供一個可自訂字元數、圖片寬高的驗證碼生成類別 DrawValImg,支援取得驗證碼圖片 (GetImgWithValidateCode) 及驗證使用者輸入 (IsRight),不區分大小寫。
類別包含四個建構子,分別支援無參數、指定字元數、指定寬高、指定字元數與寬高。預設字元數 5、寬 200、高 45、字體大小 20。
public DrawValImg() { }
public DrawValImg(int charNum) { this.CharNum = charNum; }
public DrawValImg(int width, int height) { this.width = width; this.height = height; }
public DrawValImg(int charNum, int width, int height) { this.CharNum = charNum; this.width = width; this.height = height; }
GetValidateCode() 從預設字元集 (排除易混淆字元) 隨機抽取指定長度字串,存於 ValidStr。
GetImgWithValidateCode() 流程:
1. 產生隨機字串
2. 依字元數與圖片尺寸計算字體大小
3. 建立 Bitmap 與 Graphics 物件
4. 設定淡色背景、繪製干擾線條
5. 使用 10 種字體隨機繪製各字元
6. 套用扭曲效果 (TwistImage)
7. 以 GIF 格式輸出至記憶體流並回傳 Image 物件
GetControllableColor(int colorBase) 確保 RGB 分量皆大於基值,產生淡色系背景或深色前景。
TwistImage 以正弦波在位移像素座標,造成視覺扭曲,增加辨識難度。
IsRight(string inputValCode) 將輸入與產生字串轉大寫比對,回傳布林值。
var validator = new DrawValImg(4, 150, 50);
Image img = validator.GetImgWithValidateCode();
// 將 img 輸出至網頁或儲存
bool ok = validator.IsRight(userInput);
此類庫完整封裝驗證碼生成與驗證邏輯,可直接整合至 ASP.NET 或 WinForms 專案。