说到验证码,应该是老话重提,不用说,大家都知道验证码的重要性,以前做asp的时候,直接调用别人写的几个asp文件,然后<img src="xxx.asp" />就ok了,并没有深入的去学习这些验证码是如何生成的,直到学习了.net的GDI+,看了下验证码的代码之后,才明了,其实验证码就是那么回事,下面我们废话不多说进入今天复习的正题
验证码无非是用到了.net类库中的System.Drawing中的一些类,比如Imaging,Drawing2D等
下面我们通过一个asp.net验证码的例子来了解一下这些数字是如何生成的,又是如何将之画上图片上去的
Code
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.Drawing2D;
using System.Drawing.Imaging;
public partial class CheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.CreateCheckCodeImage(GenerateCheckCode());
}
//生成随机数
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
if (number % 2 == 0) // 如果是个偶数
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
Session["CheckCode"] = checkCode;
return checkCode;
}
//将随机数写入图片
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
//Math.Celling方法是返回大于或等于指定数字的最小整数
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 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);
//画线需要四个值,即起点的坐标(x1,y1)和末点的坐标(x2,y2)
g.DrawLine(new Pen(Color.GreenYellow), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Verdana", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
//通过定义一个笔刷来画一个长方形
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.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 < 80; 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.Red), 0, 0, image.Width - 1, image.Height - 1);
//定义一个内存流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);//图片保存格式为gif
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());//将二进制字符串写入Http输出流中
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
代码也不难,大家可以看下Drawing类,常用的画图方法我都标明了
我这边是将随机数写入session中,当然你也可以写入cookie
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
要使用验证码也很容易,只要将之保存为xxx.aspx
使用的时候<img src="xxx.aspx" />就ok了