閱讀1007 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Asp.net中GDI+生成驗證碼

Register.aspx
 
// 當點擊驗證碼圖片時,自動重新導向一次authcode.aspx,就重新刷新一次驗證碼
$('#authimage').click(function() {
$(this).attr("src", "authcode.aspx");
 });
 
 
驗證碼:<input type="text" name="authcode" />
<img src="authcode.aspx" width="60px" height="30px" />
注意,這個驗證碼圖片的路徑是一個動態頁麵!我們就在這個動態頁麵中利用GDI+技術繪製出驗證碼
 
authcode.cs
public partial class authcode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // 驗證碼中可能出現的字符
            string authCodeString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            // 驗證碼字符集合長度
            int length = authCodeString.Length;
            // 繪製字符字體
            Font f = new Font("宋體", 24, FontStyle.Bold);
            // 繪製驗證碼的畫刷對象
            Brush b = null;
            // 繪製驗證碼的顏色
            Color brushColor = new Color();
            Bitmap image = new Bitmap(80, 40);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.Gray);// 設置背景
            
            string authCode = string.Empty;// 整個顯示給用戶的驗證碼
            string code = string.Empty;    // 當前繪製的驗證碼
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                // 取餘保證current長度不會超過驗證碼字符集合長度
                int current = random.Next((DateTime.Now.Millisecond) % length);
               
                // 驗證碼字符集合任意截取一個字符
                code = authCodeString.Substring(current, 1);
                authCode += code;
                brushColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));
                b = new SolidBrush(brushColor);
               
                // 繪製剛剛得到的字符串
                g.DrawString(code, f, b, i * 15, 2);
            }
            Response.Clear();
            Response.ContentType = "image/pjpeg";
            // 將對象保存到Response輸出流中
            image.Save(Response.OutputStream, ImageFormat.Jpeg);
            image.Dispose();
            Session["authCode"] = authCode; // 在服務器端保存驗證碼,用來比較
            Response.End();
        }
    }

 

 

最後更新:2017-04-02 22:16:10

  上一篇:go 係統測試時有關日期和時間
  下一篇:go 照鏡子 - 內功修煉