验证码图片的绘制
做个好几个网站了,但真正在开发过程中一般主要写业务逻辑的,很少去涉及这个。今天花了几分钟帮朋友弄了个验证码的绘制,其实网上很多例子。在网站开发过程中,验证码技术是保护网站安全的最基本环节,它可以防止非法人员利用注册攻击公交或登入工具来攻击网站。记得几个月前,才和几位朋友研究图片的识别,OCR识别,其主要就是针对网上这些验证码进行识别自动注册。当然自动识别还是比这个难多了,还在研究中,暂时先研究绘制的。
(一)GenerateCode方法:主要是用来产生随机字符串。
/// <summary>
/// 随机生成字符串
/// </summary>
/// <param name="number">字符串长度</param>
/// <returns></returns>
protected string GenerateCode(int number)
{
string checkCode = string.Empty;
string vChar="0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] vcArray = vChar.Split(',');
int temp = -1;//记录上次随机数值,尽量避免产生几个一样的随机数
Random rand = new Random();
for (int i = 1; i < number+1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(vcArray.Length);
if (temp != -1 && temp == t)
{
return GenerateCode(number);
}
temp = t;
checkCode += vcArray[t];
}
Response.Cookies.Add(new HttpCookie("CheckCode",checkCode));
(二)将随机生成的字符串转化成验证码图片
/// <summary>
/// 生成验证码图片
/// </summary>
/// <param name="checkCode">随机字符串</param>
private void CreateCheckImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == string.Empty)
{
return;
}
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*12.5)),22);
Graphics g = Graphics.FromImage(image);
try
{
Random radom = new Random();
g.Clear(Color.White);
for (int i = 0; i < 2; i++)
{
int x1 = radom.Next(image.Width);
int x2 = radom.Next(image.Width);
int y1 = radom.Next(image.Height);
int y2 = radom.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, (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(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 50; i++)
{
int x = radom.Next(image.Width);
int y = radom.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(radom.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
catch { }
finally
{
g.Dispose();
image.Dispose();
}
}
最后在网页中添加一个Image控件,用来显示验证码图片,并将其的ImageUrl属性设置为验证码页面的名称。