c#

位置:IT落伍者 >> c# >> 浏览文章

C#中生成验证码的类


发布日期:2021年03月03日
 
C#中生成验证码的类

在很多网站中都会用到验证码的功能来防止非法注册用户下面我就提供一个生成验证码的类

代码如下using Systemusing SystemDatausing SystemConfigurationusing SystemCollectionsusing SystemWebusing SystemWebSecurityusing SystemWebUIusing SystemWebUIWebControlsusing SystemWebUIWebControlsWebPartsusing SystemWebUIHtmlControlsusing SystemDrawing

public partial class checkcode SystemWebUIPage { protected void Page_Load(object sender EventArgs e)

{ CreateCheckCodeImage(GenerateCheckCode())}

private string GenerateCheckCode()

{ int numberchar codestring checkCode = StringEmptySystemRandom random = new Random()

for (int i = i < i++)

{ number = randomNext()

if (number % ==

code = (char)( + (char)(number % ))else code = (char)(A + (char)(number % ))

checkCode += codeToString()} ResponseCookiesAdd(new HttpCookie(CheckCode checkCode))return checkCode}

private void CreateCheckCodeImage(string checkCode)

{ if (checkCode == null || checkCodeTrim() == StringEmpty)

returnSystemDrawingBitmap image = new SystemDrawingBitmap((int)MathCeiling((checkCodeLength * )) Graphics g = GraphicsFromImage(image)try { //生成随机生成器Random random = new Random()//清空图片背景色gClear(ColorWhite)//画图片的背景噪音线for (int i = i < i++)

{ int x = randomNext(imageWidth)int x = randomNext(imageWidth)int y = randomNext(imageHeight)int y = randomNext(imageHeight)gDrawLine(new Pen(ColorBlack) x y x y} Font font = new SystemDrawingFont(Arial (SystemDrawingFontStyleBold | SystemDrawingFontStyleItalic))SystemDrawingDrawingDLinearGradientBrush brush = new SystemDrawingDrawingDLinearGradientBrush(new Rectangle( imageWidth imageHeight) ColorBlue ColorDarkRed f true)gDrawString(checkCode font brush //画图片的前景噪音点for (int i = i < i++)

{ int x = randomNext(imageWidth)int y = randomNext(imageHeight)imageSetPixel(x y ColorFromArgb(randomNext()))} //画图片的边框线gDrawRectangle(new Pen(ColorSilver) imageWidth imageHeight SystemIOMemoryStream ms = new SystemIOMemoryStream()imageSave(ms SystemDrawingImagingImageFormatGif)ResponseClearContent()ResponseContentType = image/GifResponseBinaryWrite(msToArray())} finally { gDispose()imageDispose()}

}

上一篇:借用VB的My,C#照样条条大路通罗马

下一篇:通过事例学习.net的WebForms技术(一)