Posted on 2007-07-04 13:11
车神 阅读(68)
评论(0) 编辑 收藏 网摘
图片验证码类:


using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Lover_Data.Util


{

/**//// <summary>
/// ValidateImage 的摘要说明。
/// </summary>
public class ValidateImage

{
public ValidateImage()

{
//
// TODO: 在此处添加构造函数逻辑
//
}


/**//// <summary>
/// 获得生成的图片的MemoryStream
/// </summary>
/// <param name="nLen">验证码长度</param>
/// <param name="strKey">输出参数,验证码的内容</param>
/// <returns>返回要输出到浏览器的流</returns>
public MemoryStream GenerateVerifyImage(int nLen,out string strKey)

{
int nBmpWidth = 13*nLen+5;
int nBmpHeight = 25;
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(nBmpWidth,nBmpHeight);

// 1. 生成随机背景颜色
int nRed,nGreen,nBlue; // 背景的三元色
System.Random rd = new Random((int)System.DateTime.Now.Ticks);
nRed = rd.Next(255)%128+128;
nGreen = rd.Next(255)%128+128;
nBlue = rd.Next(255)%128+128;

// 2. 填充位图背景
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
graph.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(nRed,nGreen,nBlue)),0,0,nBmpWidth,nBmpHeight);

// 3. 绘制干扰线条,采用比背景略深一些的颜色
int nLines = 3;
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(nRed-17,nGreen-17,nBlue-17),2);
for(int a =0;a< nLines;a++)

{
int x1 = rd.Next() % nBmpWidth;
int y1 = rd.Next() % nBmpHeight;
int x2 = rd.Next() % nBmpWidth;
int y2 = rd.Next() % nBmpHeight;
graph.DrawLine(pen,x1,y1,x2,y2);
}

// 采用的字符集,可以随即拓展,并可以控制字符出现的几率
string strCode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

strKey = "";
// 4. 循环取得字符,并绘制
for(int i=0;i < nLen;i++)

{
int x = (i*13 + rd.Next(3));
int y = rd.Next(4) + 1;

// 确定字体
System.Drawing.Font font = new System.Drawing.Font("Courier New",12 + rd.Next()%4,System.Drawing.FontStyle.Bold);
char c = strCode[rd.Next(strCode.Length)]; // 随机获取字符
strKey += c.ToString();

// 绘制字符
graph.DrawString(c.ToString(),font,new SolidBrush(System.Drawing.Color.FromArgb(nRed-60+y*3,nGreen-60+y*3,nBlue-40+y*3)),x,y);
}
// 5. 输出流
System.IO.MemoryStream bstream = new System.IO.MemoryStream();
bmp.Save(bstream,System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
graph.Dispose();
return bstream;
}

}
}

使用:
首先新建一个页面WebForm1.aspx,在Page_Load中加入:


private void Page_Load(object sender, System.EventArgs e)

{
ValidateImage vi = new ValidateImage();
string str;
MemoryStream ms = vi.GenerateVerifyImage(4,out str);
Session["Validate"] = str;
Response.ClearContent();
Response.ContentType = "images/Jpeg";
Response.BinaryWrite(ms.ToArray());
Response.End();
ms.Close();
}
然后,在需要图片验证码的页面HTML中放一个img,代码如下:
img参数:id="MzImgExpPwd" src="Util/ShowValidateImage.aspx?temp='+ (new Date().getTime().toString(36)) +'"
更换图片的连接参数:onclick="document.getElementById('MzImgExpPwd').src='Util/ShowValidateImage.aspx?temp='+ (new Date().getTime().toString(36)); return false" href="#"
A onclick="document.getElementById('MzImgExpPwd').src='Util/ShowValidateImage.aspx?temp='+ (new Date().getTime().toString(36)); return false" href="#">换图片