ASP.net 验证码( C# )
ValidateCode : System.Web.UI.Page
{
Page_Load( sender, System. e )
{
.CreateCheckCodeImage( GenerateCheckCode( ) );
}
#region web 窗体设计器生成的代码
OnInit( e )
{
InitializeComponent( );
.OnInit( e );
}
InitializeComponent( )
{
.Load += System.EventHandler( .Page_Load );
}
#endregion
GenerateCheckCode( )
{
number;
code;
checkCode = String.Empty;
System.Random random = Random( );
( i=0; i<5; i++ )
{
number = random.Next( );
( number % 2 == 0 )
code = ( )( '0' + ( )( number % 10 ) );
code = ( )( 'A' + ( )( number % 26 ) );
checkCode += code.ToString( );
}
Response.Cookies.Add( HttpCookie( "CheckCode", checkCode ) );
checkCode;
}
CreateCheckCodeImage( checkCode )
{
( checkCode == || checkCode.Trim( ) == String.Empty )
;
System.Drawing.Bitmap image = System.Drawing.Bitmap( ( )Math.Ceiling( ( checkCode.Length * 12.5 ) ), 22 );
Graphics g = Graphics.FromImage( image );
{
Random random = Random( );
g.Clear( Color.White );
( i=0; i<25; i++ )
{
x1 = random.Next( image.Width );
x2 = random.Next( image.Width );
y1 = random.Next( image.Height );
y2 = random.Next( image.Height );
g.DrawLine( Pen( Color.Silver ), x1, y1, x2, y2 );
}
Font font = System.Drawing.Font( "Arial", 12, ( System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic ) );
System.Drawing.Drawing2D.LinearGradientBrush brush = System.Drawing.Drawing2D.LinearGradientBrush( Rectangle( 0, 0, image.Width, image.Height ), Color.Blue, Color.DarkRed, 1.2f, );
g.DrawString( checkCode, font, brush, 2, 2 );
( i=0; i<100; i++ )
{
x = random.Next( image.Width );
y = random.Next( image.Height );
image.SetPixel( x, y, Color.FromArgb( random.Next( ) ) );
}
g.DrawRectangle( Pen( Color.Silver ), 0, 0, image.Width - 1, image.Height - 1 );
System.IO.MemoryStream ms = System.IO.MemoryStream( );
image.Save( ms, System.Drawing.Imaging.ImageFormat.Gif );
Response.ClearContent( );
Response.ContentType = "image/Gif";
Response.BinaryWrite( ms.ToArray( ) );
}
{
g.Dispose( );
image.Dispose( );
}
}
}