1. 程式人生 > >mvc 登入時點選切換驗證碼圖片

mvc 登入時點選切換驗證碼圖片

將生成的隨機數寫入影象檔案  

         /// <summary>  
        /// 該方法是將生成的隨機數寫入影象檔案  
        /// </summary>  
        /// <param name="VNum">VNum是一個隨機數</param>  
        public MemoryStream Create(out string VNum)
        {
            VNum = RndNum(4);
            Bitmap Img = null
; Graphics g = null; MemoryStream ms = null; System.Random random = new Random(); //驗證碼顏色集合 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //驗證碼字型集合 string
[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋體" }; //定義影象的大小,生成影象的例項 Img = new Bitmap((int)VNum.Length * 18, 32); g = Graphics.FromImage(Img);//從Img物件生成新的Graphics物件 g.Clear(Color.White);//背景設為白色 //在隨機位置畫背景點
for (int i = 0; i < 100; i++) { int x = random.Next(Img.Width); int y = random.Next(Img.Height); g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1); } //驗證碼繪製在g中 for (int i = 0; i < VNum.Length; i++) { int cindex = random.Next(7);//隨機顏色索引值 int findex = random.Next(5);//隨機字型索引值 Font f = new System.Drawing.Font(fonts[findex], 15, System.Drawing.FontStyle.Bold);//字型 Brush b = new System.Drawing.SolidBrush(c[cindex]);//顏色 int ii = 4; if ((i + 1) % 2 == 0)//控制驗證碼不在同一高度 { ii = 2; } g.DrawString(VNum.Substring(i, 1), f, b, 3 + (i * 12), ii);//繪製一個驗證字元 } ms = new MemoryStream();//生成記憶體流物件 Img.Save(ms, ImageFormat.Jpeg);//將此影象以Png影象檔案的格式儲存到流中 //回收資源 g.Dispose(); Img.Dispose(); return ms; }
View Code

控制器中加入方法

         /// <summary>
        /// 驗證碼
        /// </summary>
        /// <returns></returns>
        public FileContentResult ValidateCode()
        {
            string code = "";
            System.IO.MemoryStream ms = new Models.verify_code().Create(out code);
            Session["gif"] = code;//驗證碼儲存在Session中,供驗證。
            Response.ClearContent();//清空輸出流
            return File(ms.ToArray(), @"image/png");
        }
View Code

js引用

<img id="imgVerify" src="/Sys/Account/ValidateCode" alt="看不清?點選更換" onclick="this.src = this.src + '?'" style="vertical-align:middle;" />

ok了。