首页 > 代码库 > 生成图片验证码

生成图片验证码

 /// <summary>
        /// 图片验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateCode()
        {
            byte[] data = http://www.mamicode.com/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);
        }

 

生成图片验证码