| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591 |
- 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; }
- /// <summary>
- /// 验证码的最大长度
- /// </summary>
- public int MaxLength => 10;
- /// <summary>
- /// 验证码的最小长度
- /// </summary>
- public int MinLength => 4;
- /// <summary>
- /// 生成验证码
- /// </summary>
- /// <param name="length">指定验证码的长度</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 创建验证码的图片
- /// </summary>
- /// <param name="validateCode">验证码</param>
- 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();
- }
- }
- /// <summary>
- /// 创建验证码的图片
- /// </summary>
- /// <param name="validateCode">验证码</param>
- /// <param name="context">要输出到的page对象</param>
- 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();
- }
- }
- /// <summary>
- /// 得到验证码图片的长度
- /// </summary>
- /// <param name="validateNumLength">验证码的长度</param>
- /// <returns></returns>
- public static int GetImageWidth(int validateNumLength)
- {
- return (int)(validateNumLength * 16.0);
- }
- /// <summary>
- /// 得到验证码的高度
- /// </summary>
- /// <returns></returns>
- public static double GetImageHeight()
- {
- return 24;
- }
- }
- public class ValidateCodePic
- {
- private readonly List<string> _fuHao;
- private readonly List<Color> _color;
- private readonly List<Font> _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<string>() { "加", "减" };
- _color = new List<Color>() {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<Font>() {
- // 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)
- };
- }
- /// <summary>
- /// 构造函数重载
- /// </summary>
- /// <param name="isExp">默认 true 公式图片 、falae 字母图片</param>
- /// <param name="width"></param>
- /// <param name="height"></param>
- /// <param name="isByte">默认true返回数据流、false返回图片</param>
- 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<string>() {"加","减"};
- // _color = new List<Color>() {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<Font>() {
- // // 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<byte[], string> 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<byte[], string>(stream.ToArray(), sb.ToString());
- }
- finally
- {
- g.Dispose();
- b.Dispose();
- }
-
- }
-
- public Tuple<Bitmap, string> 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<Bitmap, string>(b, sb.ToString());
- }
- finally
- {
- g.Dispose();
- b.Dispose();
- }
-
- }
- public Tuple<Bitmap, string> 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<Bitmap, string>(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)]);
- }
- }
- /// <summary>
- /// 随机字符
- /// </summary>
- /// <returns></returns>
- private int RandomToInt(int i)
- {
- return _r.Next(0, i);
- }
- public Tuple<byte[], string> 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<byte[], string>(stream.ToArray(), GetResult(fuhao, frist, scoend).ToString());
- }
- finally
- {
- g.Dispose();
- b.Dispose();
- }
-
- }
- public Tuple<Bitmap, string> 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<Bitmap, string>(b, GetResult(fuhao, frist, scoend).ToString());
- }
- finally
- {
- g.Dispose();
- b.Dispose();
- }
- }
- public Tuple<Bitmap, string> 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<Bitmap,string>(b, GetResult(fuhao, frist, scoend).ToString());
- }
- /// <summary>
- /// 随机得到数字
- /// </summary>
- /// <returns></returns>
- 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;
- }
- }
-
- }
|