欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用GDI+實現(xiàn)生成驗證碼

 更新時間:2022年05月16日 09:29:18   作者:springsnow  
這篇文章介紹了C#使用GDI+實現(xiàn)生成驗證碼的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、概述

一般處理程序 ashx :它沒有服務器控件,用response輸出什么就是什么。

生成驗證碼原理:產生隨機字符,并將字符生成為圖片,同時儲存到Session里去,然后驗證用戶輸入的內容是否與Session中的驗證碼相符即可。

效果圖:用戶可以點擊切換驗證碼信息。

二、一般處理程序

    public class CheckCodeHandler : IHttpHandler, IRequiresSessionState//使用到Session,需要實現(xiàn)此接口IRequiresSessionState
    {
        private int intLength = 5;        //長度
        private string strIdentify = "Identify"; //隨機字串存儲鍵值,以便存儲到Session中


        /// <summary>
        /// 生成驗證圖片核心代碼
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            //背景用白色填充
            Bitmap map = new Bitmap(200, 60);
            Graphics g = Graphics.FromImage(map);
            g.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);

            //將隨機生成的字符串繪制到圖片上
            string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            Random r = new Random();
            StringBuilder s = new StringBuilder();
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);

            for (int i = 0; i < intLength; i++)
            {
                s.Append(letters.Substring(r.Next(0, letters.Length - 1), 1));
                g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));
            }
            font.Dispose();
            context.Session[strIdentify] = s.ToString(); //先保存在Session中,驗證與用戶輸入是否一致

            //生成干擾線條,混淆背景
            Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
            for (int i = 0; i < 10; i++)
            {
                g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
            }
            pen.Dispose();

            //設置輸出流圖片格式
            context.Response.ContentType = "image/gif";
            map.Save(context.Response.OutputStream, ImageFormat.Gif);
            map.Dispose();

            context.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

三、在頁面調用

<img src="CheckCodeHandler.ashx" alt="驗證碼" style="width: 60px; height: 24px" />
if (this.TextBox1.Text.ToUpper().Trim() != Session["strIdentify"].ToString().ToUpper().Trim())
{
    Response.Write("<script>alert('驗證碼不正確')</script>");
}
else
{
    Response.Write("<script>alert('登錄成功')</script>");
}

到此這篇關于C#使用GDI+實現(xiàn)生成驗證碼的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論