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

C# 用 GDI+ 繪製驗證碼 (2) — RandomGeneratorStyle 列舉與 DrawString 繪製核心

     編輯:關於C語言

驗證碼字元集列舉


public enum RandomGeneratorStyle {
    Number,                 // 純數字
    NumberAndChar,          // 數字 + 大小寫字母
    NumberAndCharIgnoreCase // 數字 + 大寫字母
}

GDI+ 繪製核心:Graphics.DrawString()

建立位圖 → 取得 Graphics → 產生隨機字串 → 存 Session → 設定字體/筆刷 → DrawString → 輸出 JPEG 串流:


public static void Generate(RandomGeneratorStyle style, int length, Page curPage) {
    Bitmap bmp = new Bitmap((int)Math.Ceiling(length * 12.5), 20);
    Graphics g = Graphics.FromImage(bmp);
    string strCode = RandomGenerator.Generate(style, length);
    curPage.Session["yzmCode"] = strCode;
    Font font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
    SolidBrush brush = new SolidBrush(Color.White);
    g.DrawString(strCode, font, brush, 0, 0); // 關鍵繪製步驟
    bmp.Save(curPage.Response.OutputStream, ImageFormat.Jpeg);
    g.Dispose();
}

測試效果

新增 `yzm.aspx`,`Page_Load` 呼叫 `Generate`:

圖 1:驗證碼輸出範例。

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