目前,机器识别验证码已经相当强大了,比较常见的避免被机器识别的方法,就是将验证码的字符串连到一起,这样就加大的识别的难度,毕竟机器没有人工智能。我找了很多的.net生成图片验证码的例子,后来经过一些修改和整理,差不多满足了我的要求:图片有噪音点,每个字符的字体随机,颜色随机,字符部分重叠。
那么如何实现呢?
1. 首先,验证码图片标签<img>链接到生成图片的aspx页面,如:
[c-sharp] view plaincopyprint?
- <img src="IdentifyingCode.aspx" src="IdentifyingCode.aspx" style="vertical-align:bottom; margin-bottom:1px; cursor: pointer;" style="vertical-align:bottom; margin-bottom:1px; cursor: pointer;" alt="点击刷新" onclick="javascript:var time = new Date().getTime(); this.src=this.src + ‘?‘ + time;">
onclick事件的作用在于,点击后,会因为src变化,而重新载入生成图片的页面,以达到更新验证码的效果。
2. 生成图片页面代码,aspx页面不需要添加任何代码,aspx.cs代码,在PageLoad方法中,生成图片。
[c-sharp] view plaincopyprint?
- using System;
- using System.Data;
- using System.Configuration;
- using System.Collections;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- namespace ATA.OLSD.OrgMng.WebSite
- {
- public partial class IdentifyingCode : System.Web.UI.Page
- {
- private void Page_Load(object sender, System.EventArgs e)
- {
- string randomcode = this.CreateRandomCode(4);
- Response.Cookies.Add(new HttpCookie("CheckCode", randomcode));
- //ViewState["ValidateCode"] = randomcode; // Session、Cookie、ViewState都可保存,根据实际情况定
- this.CreateImage(randomcode);
- }
- /// <summary>
- /// 生成随机码
- /// </summary>
- /// <param name="length">随机码个数</param>
- /// <returns></returns>
- private string CreateRandomCode(int length)
- {
- int rand;
- char code;
- string randomcode = String.Empty;
- //生成一定长度的验证码
- System.Random random = new Random();
- for (int i = 0; i < length; i++)
- {
- rand = random.Next();
- if (rand % 3 == 0)
- {
- code = (char)(‘A‘ + (char)(rand % 26));
- }
- else
- {
- code = (char)(‘0‘ + (char)(rand % 10));
- }
- randomcode += code.ToString();
- }
- return randomcode;
- }
- /// <summary>
- /// 创建随机码图片
- /// </summary>
- /// <param name="randomcode">随机码</param>
- private void CreateImage(string randomcode)
- {
- int randAngle = 45; //随机转动角度
- int mapwidth = (int)(randomcode.Length * 16);
- Bitmap map = new Bitmap(mapwidth, 28); //创建图片背景,设置其长宽
- Graphics graph = Graphics.FromImage(map);
- graph.Clear(Color.AliceBlue);
- graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
- Random rand = new Random();
- // 生成背景噪点
- Pen blackPen = new Pen(Color.LightGray, 0);
- for (int i = 0; i < 50; i++)
- {
- int x = rand.Next(0, map.Width);
- int y = rand.Next(0, map.Height);
- graph.DrawRectangle(blackPen, x, y, 1, 1);
- }
- //验证码旋转,防止机器识别
- char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组
- //文字距中
- StringFormat format = new StringFormat(StringFormatFlags.NoClip);
- format.Alignment = StringAlignment.Center;
- format.LineAlignment = StringAlignment.Center;
- // 定义随机颜色列表
- Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
- // 定义随机字体字体
- string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
- for (int i = 0; i < chars.Length; i++)
- {
- int cindex = rand.Next(7);
- int findex = rand.Next(5);
- Font f = new System.Drawing.Font(font[findex], 16, System.Drawing.FontStyle.Bold); // 字体样式(参数2为字体大小)
- Brush b = new System.Drawing.SolidBrush(c[cindex]);
- Point dot = new Point(11, 11); // 括号内数值越大,字符间距越大
- float angle = rand.Next(0, randAngle); // 转动的度数,如果将0改为-randAngle,那么旋转角度为-45度~45度
- graph.TranslateTransform(dot.X, dot.Y);
- graph.RotateTransform(angle);
- graph.DrawString(chars[i].ToString(), f, b, 2, 6, format); // 第4、5个参数控制左、上间距
- graph.RotateTransform(-angle);
- graph.TranslateTransform(2, -dot.Y);
- }
- //生成图片
- System.IO.MemoryStream ms = new System.IO.MemoryStream();
- map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
- Response.ClearContent();
- Response.ContentType = "image/gif";
- Response.BinaryWrite(ms.ToArray());
- graph.Dispose();
- map.Dispose();
- }
- }
- }
可根据其中注释来修改验证码的字符大小、旋转角度、字体、颜色等等。每次重新加载该页面,将会得到新的验证码,并保存在session或cookie中,校验时,从session或cookie中读取即可。
效果如下图所示:
可点击刷新。
时间: 2024-10-07 05:55:50