在很多網站中都會用到驗證碼的功能來防止非法注冊用戶下面我就提供一個生成驗證碼的類
代碼如下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()}
}
From:http://tw.wingwit.com/Article/program/net/201311/13063.html