码迷,mamicode.com
首页 > 其他好文 > 详细

生成图片验证码

时间:2017-06-29 17:29:31      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:rect   span   get   dom   噪点   file   验证码   returns   return   

 /// <summary>
        /// 图片验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateCode()
        {
            byte[] data = null;
            string code = RandCode(5);
            TempData["code"] = code;
            //画板
            Bitmap imgCode = new Bitmap(80, 25);
            //画笔
            Graphics gp = Graphics.FromImage(imgCode);
            //背景为白色
            gp.FillRectangle(Brushes.White, 0, 0, imgCode.Width, imgCode.Height);
            gp.DrawString(code, new Font("宋体", 14), Brushes.Black, new PointF(10, 2));
            Random rand = new Random();
            //绘制燥线
            for (int i = 0; i < 5; i++)
            {
                gp.DrawLine(new Pen(RandColor()), rand.Next(imgCode.Width), rand.Next(imgCode.Height), rand.Next(imgCode.Width), rand.Next(imgCode.Height));
            }
            //绘制噪点
            for (int i = 0; i < 50; i++)
            {
                imgCode.SetPixel(rand.Next(imgCode.Width), rand.Next(imgCode.Height), RandColor());
            }
            gp.Dispose();
            MemoryStream ms = new MemoryStream();
            imgCode.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            data = ms.GetBuffer();
            return File(data, "image/jepg");
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        private string RandCode(int len)
        {
            StringBuilder sb = new StringBuilder();
            string words = "0987654321qwerghjzxcvb";
            Random random = new Random();
            for (int i = 0; i < len; i++)
            {
                char ch = words[random.Next(0, words.Length)];
                if (sb.ToString().Contains(ch))
                {
                    i--;
                    continue;
                }
                sb.Append(ch + "");
            }
            return sb.ToString();
        }

        private Color RandColor()
        {
            Random random = new Random();
            int red = random.Next(10, 200);
            int green = random.Next(10, 200);
            int blue = random.Next(10, 200);
            return Color.FromArgb(red, green, blue);
        }

 

生成图片验证码

标签:rect   span   get   dom   噪点   file   验证码   returns   return   

原文地址:http://www.cnblogs.com/baixiaoguang/p/7094708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!