生成验证码及调用


     //创建验证码
        public static string CreateValidateCode()
        {
            string checkCode = string.Empty;
            Random rnd = new Random(DateTime.Now.Millisecond);
            char[] chr = { 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            for (int i = 0; i < 5; i++)
            {
                checkCode += chr[rnd.Next(chr.Length)];
            }
            return checkCode;
        }
View Code

        //根据验证码画图片
        public static byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap bmp = new Bitmap(80, 24);
            Graphics g = Graphics.FromImage(bmp);
            MemoryStream ms = new MemoryStream();
            try
            {
                Random random = new Random(DateTime.Now.Millisecond);
                g.Clear(Color.White);
                for (int i = 0; i < 6; i++)
                {
                    int x1 = random.Next(bmp.Width);
                    int x2 = random.Next(bmp.Width);
                    int y1 = random.Next(bmp.Height);
                    int y2 = random.Next(bmp.Height);

                    int Color_r = random.Next(255);
                    int Color_g = random.Next(255);
                    int Color_b = random.Next(255);
                    g.DrawLine(new Pen(Color.FromArgb(Color_r, Color_g, Color_b)), x1, y1, x2, y2);
                }
                g.DrawString(validateCode, new Font(FontFamily.GenericSerif, 16), Brushes.Black, 0, 0);                
                bmp.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();                
            }
        }
View Code
 
1 //mvc调用
2 public ActionResult GetValidateCode()
3 {
4        Session["CheckCode"] = null;
5        string checkCode = WebUtility.CreateValidateCode();
6        byte[] bytes = WebUtility.CreateValidateGraphic(checkCode);
7        Session["CheckCode"] = checkCode;
8        return File(bytes, @"image/jpeg");            
9 }
View Code
 
 1 <div class="jumbotron">
 2     <p>验证码:<img alt="" align="middle" id="valiCode" /></p>
 3 </div>
 4 <script type="text/javascript">
 5     $(function () {
 6         $("#valiCode").bind("click", function () {
 7             this.src = "/Account/GetValidateCode?time=" + (new Date()).getTime();
 8         });
 9         $("#valiCode").click();
10     });
11 </script>
View Code
 
寻寻觅觅转流年,磕磕碰碰道缘浅。 揽几缕、轻挽起,暮暮朝朝与君语。
原文地址:https://www.cnblogs.com/bingshao/p/14097299.html