验证码不用输出太多的HTML代码,直接创建一个一般处理程序,直接上代码
public class VCode : IHttpHandler
{ HttpContext context = null;
public void ProcessRequest(HttpContext context)
{
this.context = context;
CreateVImage(CreateRandomNum());
} #region 创建随机数 CreateRandomNum(int NumCount)
/// <summary>
/// 创建随机数
/// </summary>
/// <param name="NumCount">条形码上的数字个数</param>
/// <returns>返回随机数</returns>
private string CreateRandomNum(int NumCount)
{
string allChar = "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";
string[] allCharArr = allChar.Split(',');
string randomNum = "";
int temp = -;//记录上次随机数的数值,尽量避免产生几个相同的随机数
Random random = new Random();
for (int i = ; i < NumCount; i++)
{
if (temp != -)
{
random = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = random.Next();
if (temp == t)
{
return CreateRandomNum(NumCount);
}
temp = t;
randomNum += allCharArr[t];
}
return randomNum;
}
#endregion #region 生成验证码图片 CreateVImage(string validateNum) /// <summary>
/// 生成验证码图片 CreateVImage(string validateNum)
/// </summary>
/// <param name="validateNum">验证码数字</param>
private void CreateVImage(string validateNum)
{
if (validateNum == null || validateNum.Trim() == string.Empty)
{
return;
}
//生成Bitmap图像
Bitmap image = new Bitmap(validateNum.Length * + , );
Graphics g = Graphics.FromImage(image);
try
{
//随机数生成
Random random = new Random();
//清空图片背景色,将背景色换为白色
g.Clear(Color.White);
//画图片的背景线
for (int i = ; i < ; 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(Brushes.Beige), x1, y1, x2, y2);
}
//设置字体
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));
//设置笔刷
System.Drawing.Drawing2D.LinearGradientBrush brush =
new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(, , image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
//用设置好的字体和笔刷将验证码写到图片上
g.DrawString(validateNum, font, brush, , );
//画图片上的点
for (int i = ; i < ; 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), , , image.Width, image.Height);
//创建一个内存流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//将图片保存到指定流中,并指定图片格式
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//清空缓存区所有内容输出
context.Response.ClearContent();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(ms.ToArray());
}
catch (Exception ex)
{
context.Response.Write("异常..."+ex.Message);
}
finally
{
//释放资源
g.Dispose();
image.Dispose();
} }
#endregion public bool IsReusable
{
get
{
return false;
}
}
}
ValidateCode
直接复制过去,改下类名直接可用,效果图如下:
周围黑的不是验证码生成的,截图原因而已