新建一个专门用来创建验证码图片的页面ValidateCode
aspx
它的后台cs文件代码如下
PageLoad
private void Page_Load(object sender SystemEventArgs e)
{
string checkCode = CreateRandomCode()
Session[CheckCode] = checkCode;
CreateImage(checkCode)
}
其中CreateRandomCode是自定义的函数参数代表验证码位数
private string CreateRandomCode(int codeCount)
{
string allChar = ABCDEFGHIJKLMNOPQRSTUWXYZ ;
string[] allCharArray = allCharSplit()
string randomCode = ;
int temp = ;
Random rand = new Random()
for(int i = ; i < codeCount; i++)
{
if(temp != )
{
rand = new Random(i*temp*((int)DateTimeNowTicks))
}
int t = randNext()
if(temp == t)
{
return CreateRandomCode(codeCount)
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
CreateImage也是一个自定义的函数用于生成图
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCodeLength * )
SystemDrawingBitmap image = new SystemDrawingBitmap(iwidth )
Graphics g = GraphicsFromImage(image)
Font f = new SystemDrawingFont(Arial SystemDrawingFontStyleBold)
Brush b = new SystemDrawingSolidBrush(ColorWhite)
//gFillRectangle(new SystemDrawingSolidBrush(ColorBlue)imageWidth imageHeight)
gClear(ColorBlue)
gDrawString(checkCode f b )
Pen blackPen = new Pen(ColorBlack )
Random rand = new Random()
for (int i=;i<;i++)
{
int y = randNext(imageHeight)
gDrawLine(blackPenyimageWidthy)
}
SystemIOMemoryStream ms = new SystemIOMemoryStream()
imageSave(msSystemDrawingImagingImageFormatJpeg)
ResponseClearContent()
ResponseContentType = image/Jpeg;
ResponseBinaryWrite(msToArray())
gDispose()
imageDispose()
}
//gFillRectangle(new SystemDrawingSolidBrush(ColorBlue)imageWidth imageHeight)
gClear(ColorBlue)
这两种方法都可以改变生成图片的背景颜色
下面那个for循环用来生成一些随机的水平线
在需要用到验证码的页面添加一个<asp:Image>控件即可但是要把ImageUrl指向生成验证码的页面
<asp:Image Runat=server ID=ImageCheck ImageUrl=ValidateCodeaspx></asp:Image>