using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Web; namespace CommonTool { public class ValidateCode { public ValidateCode() { Code = CreateValidateCode(4); } public string Code { get; } /// /// 验证码的最大长度 /// public int MaxLength => 10; /// /// 验证码的最小长度 /// public int MinLength => 4; /// /// 生成验证码 /// /// 指定验证码的长度 /// public string CreateValidateCode(int length) { int[] randMembers = new int[length]; int[] validateNums = new int[length]; string validateNumberStr = ""; //生成起始序列值 int seekSeek = unchecked((int)DateTime.Now.Ticks); Random seekRand = new Random(seekSeek); int beginSeek = seekRand.Next(0, Int32.MaxValue - length * 10000); int[] seeks = new int[length]; for (int i = 0; i < length; i++) { beginSeek += 10000; seeks[i] = beginSeek; } //生成随机数字 for (int i = 0; i < length; i++) { Random rand = new Random(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 = new Random(); 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; } /// /// 创建验证码的图片 /// /// 验证码 public byte[] CreateValidateGraphic(string validateCode) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 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(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(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(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 return stream.ToArray(); } finally { g.Dispose(); image.Dispose(); } } /// /// 创建验证码的图片 /// /// 验证码 /// 要输出到的page对象 public void CreateValidateGraphic(string validateCode, HttpContext context) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 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(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(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(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); image.Dispose(); } } /// /// 得到验证码图片的长度 /// /// 验证码的长度 /// public static int GetImageWidth(int validateNumLength) { return (int)(validateNumLength * 16.0); } /// /// 得到验证码的高度 /// /// public static double GetImageHeight() { return 24; } } public class ValidateCodePic { private readonly List _fuHao; private readonly List _color; private readonly List _font; private int _x; private int _y; private readonly int _width; private readonly int _height; private readonly Random _r = new Random(); public bool IsExp { get; set; } public Bitmap FileBitmap { get; set; } public byte[] FileBytes { get; set; } public string Code { get; set; } public HttpContext Context { get; set; } public ValidateCodePic() { _width = 100; _height = 40; _fuHao = new List() { "加", "减" }; _color = new List() {Color.Red,Color.Black,Color.Blue,Color.Green, ColorTranslator.FromHtml("#FF00FF"), ColorTranslator.FromHtml("#CD0000"), ColorTranslator.FromHtml("#912CEE"), ColorTranslator.FromHtml("#00F5FF"), ColorTranslator.FromHtml("#00FF00") }; _font = new List() { // ReSharper disable once PossibleLossOfFraction new Font("宋体",_width/8,FontStyle.Bold), // ReSharper disable once PossibleLossOfFraction new Font("楷体",_width/8,FontStyle.Italic), // ReSharper disable once PossibleLossOfFraction new Font("新宋体",_width/8,FontStyle.Regular) }; } /// /// 构造函数重载 /// /// 默认 true 公式图片 、falae 字母图片 /// /// /// 默认true返回数据流、false返回图片 public ValidateCodePic(int width, int height, bool isExp=true,bool isByte=true):this() { IsExp =isExp; _width = width; _height = height; if (isByte) { var tempTupleByte = IsExp ? DrawExpByte() : DrawStrByte(); FileBytes = tempTupleByte.Item1; Code = tempTupleByte.Item2; } else { var tempTupleBitmap = IsExp ? DrawExpBitmap() : DrawStrBigmap(); FileBitmap = tempTupleBitmap.Item1; Code = tempTupleBitmap.Item2; } } public ValidateCodePic(HttpContext content,int width, int height, bool isExp = true) : this() { IsExp = isExp; _width = width; _height = height; Context = content; var tempTupleContext = IsExp ? DrawExp(Context) : DrawStr(Context); FileBitmap = tempTupleContext.Item1; Code = tempTupleContext.Item2; } //public ValidateCodePic(int width=100, int height=30) //{ // _width = width; // _height = height; // _fuHao = new List() {"加","减"}; // _color = new List() {Color.Red,Color.Black,Color.Blue,Color.Green, // ColorTranslator.FromHtml("#6A5ACD"), // ColorTranslator.FromHtml("#008B8B"), // ColorTranslator.FromHtml("#556B2F"), // ColorTranslator.FromHtml("#4B0082"), // ColorTranslator.FromHtml("#20B2AA"), // ColorTranslator.FromHtml("#9ACD32"), // ColorTranslator.FromHtml("#B22222"), // ColorTranslator.FromHtml("#BA55D3"), // ColorTranslator.FromHtml("#F0E68C"), // ColorTranslator.FromHtml("#1E90FF") // }; // _font = new List() { // // ReSharper disable once PossibleLossOfFraction // new Font("宋体",width/5,FontStyle.Bold), // // ReSharper disable once PossibleLossOfFraction // new Font("楷体",width/6,FontStyle.Italic), // // ReSharper disable once PossibleLossOfFraction // new Font("新宋体",width/5,FontStyle.Regular) // }; //} public Tuple DrawStrByte() { StringBuilder sb = new StringBuilder(); Bitmap b = GetMap(_width, _height); //生成画布 Graphics g = Graphics.FromImage(b); try { //清空图片背景色 g.Clear(Color.White); //画背景图 g.FillRectangle(Brushes.Gainsboro, 0, 0, _width, _height); //画字 for (int i = 0; i < 4; i++) { string temp = RandomString(); sb.Append(temp); DrawString(g, temp); } //画干扰线 DrawGanRao(g, 40); //画干扰点 DrawGanRaoDian(b, 1000); //画图片的边框线 g.DrawRectangle(new Pen(Color.DarkGray), 0, 0, _width - 1, _height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); b.Save(stream, ImageFormat.Jpeg); //输出图片流 return new Tuple(stream.ToArray(), sb.ToString()); } finally { g.Dispose(); b.Dispose(); } } public Tuple DrawStrBigmap() { StringBuilder sb = new StringBuilder(); Bitmap b = GetMap(_width, _height); //生成画布 Graphics g = Graphics.FromImage(b); try { //清空图片背景色 g.Clear(Color.White); //画背景图 g.FillRectangle(Brushes.Gainsboro, 0, 0, _width, _height); //画字 for (int i = 0; i < 4; i++) { string temp = RandomString(); sb.Append(temp); DrawString(g, temp); } //画干扰线 DrawGanRao(g, 40); //画干扰点 DrawGanRaoDian(b, 1000); //输出图片 return new Tuple(b, sb.ToString()); } finally { g.Dispose(); b.Dispose(); } } public Tuple DrawStr(HttpContext context) { StringBuilder sb = new StringBuilder(); Bitmap b = GetMap(_width, _height); //生成画布 Graphics g = Graphics.FromImage(b); try { //清空图片背景色 g.Clear(Color.White); //画背景图 g.FillRectangle(Brushes.Gainsboro, 0, 0, _width, _height); //画字 for (int i = 0; i < 4; i++) { string temp = RandomString(); sb.Append(temp); DrawString(g, temp); } //画干扰线 DrawGanRao(g, 40); //画干扰点 DrawGanRaoDian(b, 1000); //画图片的边框线 g.DrawRectangle(new Pen(Color.DarkGray), 0, 0, _width - 1, _height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); b.Save(stream, ImageFormat.Jpeg); //输出图片流 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); b.Dispose(); } return new Tuple(b, sb.ToString()); } private Bitmap GetMap(int width, int height) { Bitmap b = new Bitmap(width, height); return b; } private string RandomString() { string s = ((char)_r.Next(65, 90)).ToString(); return s; } private void DrawString(Graphics g, string s) { Font font = _font[RandomToInt(_font.Count)]; Color color = _color[RandomToInt(_color.Count)]; _x += _width /6; _y = RandomToInt(_height/6); g.DrawString(s, font, new SolidBrush(color), new PointF(_x, _y) ); g.RotateTransform(RandomToInt(6)); } private void DrawGanRao(Graphics g, int j) { for (int i = 0; i < j; i++) { g.DrawLine(new Pen(_color[RandomToInt(_color.Count)]), RandomToInt(_width), RandomToInt(_height), RandomToInt(_width), RandomToInt(_height) ); } } private void DrawGanRaoDian(Bitmap b, int j) { for (int i = 0; i < j; i++) { b.SetPixel(RandomToInt(_width), RandomToInt(_height), _color[RandomToInt(_color.Count)]); } } /// /// 随机字符 /// /// private int RandomToInt(int i) { return _r.Next(0, i); } public Tuple DrawExpByte() { int frist = GetString(); int scoend = GetString(); string fuhao = _fuHao[RandomToInt(_fuHao.Count)]; Bitmap b = GetMap(_width, _height); Graphics g = Graphics.FromImage(b); try { //清空图片背景色 g.Clear(Color.White); g.FillRectangle(Brushes.Gainsboro, 0, 0, _width, _height); DrawString(g, frist.ToString()); DrawString(g, fuhao); DrawString(g, scoend.ToString()); DrawString(g, " = ? "); //画图片的边框线 //g.DrawRectangle(new Pen(Color.CornflowerBlue), 0, 0, _width - 1, _height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); b.Save(stream, ImageFormat.Jpeg); //输出图片流 return new Tuple(stream.ToArray(), GetResult(fuhao, frist, scoend).ToString()); } finally { g.Dispose(); b.Dispose(); } } public Tuple DrawExpBitmap() { int frist = GetString(); int scoend = GetString(); string fuhao = _fuHao[RandomToInt(_fuHao.Count)]; Bitmap b = GetMap(_width, _height); Graphics g = Graphics.FromImage(b); try { //清空图片背景色 g.Clear(Color.White); g.FillRectangle(Brushes.Gainsboro, 0, 0, _width, _height); DrawString(g, frist.ToString()); DrawString(g, fuhao); DrawString(g, scoend.ToString()); DrawString(g, " = ? "); //画图片的边框线 //g.DrawRectangle(new Pen(Color.CornflowerBlue), 0, 0, _width - 1, _height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); b.Save(stream, ImageFormat.Jpeg); //输出图片流 return new Tuple(b, GetResult(fuhao, frist, scoend).ToString()); } finally { g.Dispose(); b.Dispose(); } } public Tuple DrawExp(HttpContext context) { int frist = GetString(); int scoend = GetString(); string fuhao = _fuHao[RandomToInt(_fuHao.Count)]; Bitmap b = GetMap(_width, _height); Graphics g = Graphics.FromImage(b); try { g.Clear(Color.White); g.FillRectangle(Brushes.Gainsboro, 0, 0, _width, _height); DrawString(g, frist.ToString()); DrawString(g, fuhao); DrawString(g, scoend.ToString()); DrawString(g, "=?"); //画图片的边框线 g.DrawRectangle(new Pen(Color.DarkGray), 0, 0, _width - 1, _height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); b.Save(stream, ImageFormat.Jpeg); //输出图片流 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); b.Dispose(); } return new Tuple(b, GetResult(fuhao, frist, scoend).ToString()); } /// /// 随机得到数字 /// /// private int GetString() { return RandomToInt(50); } private int GetResult(string fuhao, int frist, int scoend) { int result = frist + scoend; switch (fuhao) { case "加": result = frist + scoend; break; case "减": result = frist - scoend; break; } return result; } } }