首页 > 代码库 > 生成图片验证码
生成图片验证码
/// <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); }
生成图片验证码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。