close

跟小安要了圖形驗證碼塞進去

今天其實完整看起來還是看不太懂

先記錄一下以後回來看

 

//View -------------------------------------------------------------------------------------------------

@*這是驗證碼的輸入欄位*@

@Html.TextBoxFor(m => m.ValidateCode, newDictionary<string, object>() { { "maxlength", "5" }, { "style", "width:70%;" } })

@*這是驗證碼的輸出圖片*@

<imgid="valiCode"src="../Account/GetValidateCode"alt="驗證碼"/>  

@*這是重新整理驗證碼的圖片*@

<imgsrc="../../Content/themes/base/images/Account/cycle_icon01.png"id="validCodeRefresh"title="重新產生驗證碼"style="cursor:pointer"/>

@*這是顯示驗證碼的檢核*@

<divclass="formalert">@Html.ValidationMessageFor(model => model.ValidateCode)</div> 

@*這是重新產生驗證碼的Script*@

     <scripttype="text/javascript">

         $(document).ready(function () {

             $("#validCodeRefresh").click(function () {

                   $("#valiCode").attr("src","../Account/GetValidateCode?time=" + (new Date()).getTime());

              });

 

              $("#validCodeRefresh").hover(function () {

                       $(this).attr("src", "../../Content/Images/Account/cycle_icon.gif")

                     },function () {

                              $(this).attr("src", "../../Content/themes/base/images/Account/cycle_icon01.png")

                       });

                     });

         </script>

//Controller  -------------------------------------------------------------------------------------------------

這是一個新的Action

#regionGetValidateCode

publicActionResult GetValidateCode()

        {

            ValidateCode vCode = newValidateCode();

            string code = vCode.CreateValidateCode(5);

            Session["ValidateCode"] = code;

            String CodeView = "";

 

            for (int i = 0; i < code.Length; i++)

            {

                CodeView = CodeView + code[i] + " ";

            }

 

            byte[] bytes = vCode.CreateValidateGraphic(CodeView);

            return File(bytes, @"image/jpeg");

        }

#endregion

//Controller2  -------------------------------------------------------------------------------------------------

要放在[HTTP Post]裡面!!!

 

#region檢核驗證碼

 

 

 

            // 檢誤驗證碼是否過時

 

            if (Session["ValidateCode"] == null)

 

            {

 

                ModelState.AddModelError("","閒置時間過長,請重新輸入");

 

                return View();

 

            }

 

 

 

            // 檢誤驗證碼是否正確

 

            if (Session["ValidateCode"].ToString() != validatecode)

 

            {

 

                ModelState.AddModelError("", "驗證碼錯誤,請重新輸入");

 

                return View();

 

            } 

 

#endregion

 

//model  -------------------------------------------------------------------------------------------------

新增一個class

using System;

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

 

namespace Recruitment.Models

{

    publicclassValidateCode

    {

        public ValidateCode()

        {

        }

 

        publicint MaxLength    //設定數字最大長度

        {

            get { return 10; }

        }

 

        publicint MinLength    //設定數字最小長度

        {

            get { return 1; }

        }

 

        publicstaticdouble GetImageWidth(int validateNumLength)  //設定圖片寬度

        {

            //return (double)(validateNumLength * 12.0);

            return (double)(validateNumLength / 2 * 17.0);

        }

 

        publicstaticint GetImageHeight()   //設定圖片高度

        {

            // return 20;

            return 26;

        }

 

        publicstring CreateValidateCode(int length)    //產生驗證碼

        {

            int[] randMembers = newint[length];

            int[] validateNums = newint[length];

            string validateNumberStr = "";

            int seekSeek = unchecked((int)DateTime.Now.Ticks);

            Random seekRand = newRandom(seekSeek);

            int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);

            int[] seeks = newint[length];

            for (int i = 0; i < length; i++)

            {

                beginSeek += 10000;

                seeks[i] = beginSeek;

            }

            //產生隨機數字

            for (int i = 0; i < length; i++)

            {

                Random rand = newRandom(seeks[i]);

                int pownum = 1 * (int)Math.Pow(10, length);

                randMembers[i] = rand.Next(pownum, Int32.MaxValue);

            }

            //讀取隨機數字

            for (int i = 0; i < length; i++)

            {

                string numStr = randMembers[i].ToString();

                int numLength = numStr.Length;

                Random rand = newRandom();

                int numPosition = rand.Next(0, numLength - 1);

                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));

            }

            //產生驗證碼

            for (int i = 0; i < length; i++)

            {

                validateNumberStr += validateNums[i].ToString();

            }

            return validateNumberStr;

        }

 

        publicbyte[] CreateValidateGraphic(string validateCode)    //建立驗證碼圖片

        {

            Bitmap image = newBitmap((int)Math.Ceiling(GetImageWidth(validateCode.Length)), GetImageHeight());

            Graphics g = Graphics.FromImage(image);

            try

            {

                //產生隨機數字

                Random random = newRandom();

                //清空圖片背景色

                g.Clear(Color.White);

                //畫圖片干擾線

                for (int i = 0; i < 25; i++)

                {

                    int x1 = random.Next(image.Width);

                    int x2 = random.Next(image.Width);

                    int y1 = random.Next(image.Height);

                    int y2 = random.Next(image.Height);

                    g.DrawLine(newPen(Color.Silver), x1, y1, x2, y2);

                }

                //Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));

                Font font = newFont("Arial", 14, (FontStyle.Bold | FontStyle.Italic));

                LinearGradientBrush brush = newLinearGradientBrush(newRectangle(0, 0, image.Width, image.Height),

                 Color.Blue, Color.DarkRed, 1.2f, true);

                g.DrawString(validateCode, font, brush, 3, 2);

                //畫圖片前景干擾線

                for (int i = 0; i < 100; i++)

                {

                    int x = random.Next(image.Width);

                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));

                }

                //畫圖片邊框線

                g.DrawRectangle(newPen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                //儲存圖片數據

                MemoryStream stream = newMemoryStream();

                image.Save(stream, ImageFormat.Jpeg);

                //輸出圖片

                return stream.ToArray();

            }

            finally

            {

                g.Dispose();

                image.Dispose();

            }

        }

    }

}

 

網路參考資料

http://www.cnblogs.com/jianjialin/archive/2009/12/16/1625780.html

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JayeChen987 的頭像
    JayeChen987

    Jaye的碎碎念

    JayeChen987 發表在 痞客邦 留言(0) 人氣()