// 随机生成指定长度的验证码字符串 public ActionResult GetValidateCode(string key) { string codeStr = GetRandomCode(); TempData[key] = codeStr; return File(GetVCode(codeStr), "image/gif"); } private static Color BackColor = Color.White; private static int Width = 75; private static int Height = 30; private Random _random; private int _brushNameIndex; public byte[] GetVCode(string codeStr) { _random = new Random(); using (Bitmap img = new Bitmap(Width, Height)) { using (Graphics g = Graphics.FromImage(img)) { g.Clear(BackColor);//绘画背景颜色 Paint_Text(g, codeStr);// 绘画文字 Paint_TextStain(img);// 绘画噪音点 g.DrawRectangle(Pens.DarkGray, 0, 0, Width - 1, Height - 1);//绘画边框 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { //将图片 保存到内存流中 img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //将内存流 里的 数据 转成 byte 数组 返回 return ms.ToArray(); } } } } /// <summary> /// 绘画文字 /// </summary> /// <param name="g"></param> private void Paint_Text(Graphics g, string code) { g.DrawString(code, GetFont(), GetBrush(), 5, 5); } /// <summary> /// 绘画文字噪音点 /// </summary> /// <param name="g"></param> private void Paint_TextStain(Bitmap b) { string[] BrushName = new string[] { "OliveDrab", "ForestGreen", "DarkCyan", "LightSlateGray", "RoyalBlue", "SlateBlue", "DarkViolet", "MediumVioletRed", "IndianRed", "Firebrick", "Chocolate", "Peru", }; for (int n = 0; n < 480; n++) { b.SetPixel(_random.Next(Width), _random.Next(Height), Color.FromName(BrushName[_brushNameIndex])); } } /// <summary> /// 随机取一个字体 /// </summary> /// <returns></returns> private Font GetFont() { string[] FontItems = new string[] { "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" }; int fontIndex = _random.Next(0, FontItems.Length); FontStyle fontStyle = GetFontStyle(_random.Next(0, 2)); return new Font(FontItems[fontIndex], 15, fontStyle); } /// <summary> /// 随机取一个笔刷 /// </summary> /// <returns></returns> private Brush GetBrush() { Brush[] BrushItems = new Brush[]{ Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru, }; int brushIndex = _random.Next(0, BrushItems.Length); _brushNameIndex = brushIndex; return BrushItems[brushIndex]; } /// <summary> /// 取一个字体的样式 /// </summary> /// <param name="index"></param> /// <returns></returns> private FontStyle GetFontStyle(int index) { switch (index) { case 0: return FontStyle.Bold; case 1: return FontStyle.Italic; default: return FontStyle.Regular; } } /// <summary> /// 取得一个 5 位的随机码 /// </summary> /// <returns></returns> public string GetRandomCode(int len = 5) { return Guid.NewGuid().ToString().Substring(0, len); }