Development of Brushless newest verification code in ASP. NET (complete code)

Source: Internet
Author: User

Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Login. aspx. cs" Inherits = "Login" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head id = "Head1" runat = "server">
<Title> No title page </title>
<Script type = "text/javascript">
Function DoFresh (){
Document. getElementById ("Image1"). src = "VerifyCode. aspx ";
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Table>
<Tr>
<Td>
Verification Code: <asp: TextBox ID = "txtValidateCode" runat = "server"> </asp: TextBox>
</Td>
<Td>
<Asp: Image ID = "Image1" runat = "server"/>
<A href = "javascript: DoFresh ();"> Why Not? </A>
</Td>
</Tr>
<Tr>
<Td align = "center" colspan = "2">
<Br/>
<Asp: Literal ID = "litErrorMsg" runat = "server"> </asp: Literal>
<Asp: Button ID = "btnSubmit" runat = "server" Text = "OK" onclick = "btnSubmit_Click"/>
</Td>
</Tr>
</Table>
</Div>
</Form>
</Body>
</Html>


Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;

Public partial class Login: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
If (! Page. IsPostBack)
{
Image1.ImageUrl = "VerifyCode. aspx ";
}
}
Protected void btnSubmit_Click (object sender, EventArgs e)
{
If (Session ["ValidateCode"]! = Null)
{
String outputValidateCode = Session ["ValidateCode"] as string;
String inputValidateCode = txtValidateCode. Text. Trim ();
If (string. Compare (outputValidateCode, inputValidateCode, true )! = 0)
{
// Response. Write ("<script> javascript: alert ('incorrect verification code! '); </Script> ");
LitErrorMsg. Text = "The entered verification code is incorrect! ";
}
Else
{
// Response. Write ("<script> javascript: alert ('the entered verification code is correct! '); </Script> ");
LitErrorMsg. Text = "The entered verification code is correct! ";
}
}
}
# Region
Private void ValidateMethod ()
{
If (Request. Cookies ["CheckCode"] = null)
{
LitErrorMsg. Text = "your browser settings have been disabled for Cookies. You must set the options that allow the browser to use Cookies before using the system. ";
LitErrorMsg. Visible = true;
Return;
}
If (String. Compare (Request. Cookies ["CheckCode"]. Value, TextBox1.Text. ToString (). Trim (), true )! = 0)
{
LitErrorMsg. Text = "<font color = red> sorry, the verification code is incorrect! </Font> ";
LitErrorMsg. Visible = true;
Return;
}
Else
{
LitErrorMsg. Text = "<font color = green> congratulations, the verification code is entered correctly! </Font> ";
LitErrorMsg. Visible = true;
}
}
# Endregion
}

// VerifyCode. aspx is the default generated code
Copy codeThe Code is as follows:
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Drawing;
Using System. Drawing. Imaging;
Using System. Drawing. Drawing2D;
Using System. IO;
Public partial class VerifyCode: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
// GenerateValidateCode ();
GenerateVerifyImage (4); // GenerateVerifyImage (int length)
}

# Region [do not forget New imitation google waveform distortion color] Verification Code Style 0 ___ GenerateValidateCode ()
Private void GenerateValidateCode ()
{
This. Length = this. length;
This. FontSize = this. fontSize;
This. Chaos = this. chaos;
This. BackgroundColor = this. backgroundColor;
This. ChaosColor = this. chaosColor;
This. CodeSerial = this. codeSerial;
This. Colors = this. colors;
This. Fonts = this. fonts;
This. Padding = this. padding;
String VNum = this. CreateVerifyCode (); // obtain the random code
Session ["ValidateCode"] = VNum. ToUpper (); // obtain the verification code for later verification
This. CreateImageOnPage (VNum, this. Context); // output image
// Cookie Authentication mode. Use Cookies to obtain the verification code value.
// Response. Cookies. Add (new HttpCookie ("CheckCode", code. ToUpper ()));
}
# Endregion
# Region verification code length (the default length of four verification codes)
Int length = 4;
Public int Length
{
Get {return length ;}
Set {length = value ;}
}
# Endregion
# Region Verification Code font size (40 pixels by default for displaying distortion effects, which can be modified by yourself)
Int fontSize = 22;
Public int FontSize
{
Get {return fontSize ;}
Set {fontSize = value ;}
}
# Endregion
# Region border population (1 pixel by default)
Int padding = 2;
Public int Padding
{
Get {return padding ;}
Set {padding = value ;}
}
# Endregion
# Whether region outputs dry points (no output by default)
Bool chaos = true;
Public bool Chaos
{
Get {return chaos ;}
Set {chaos = value ;}
}
# Endregion
# Region output dry point color (gray by default)
Color chaosColor = Color. LightGray;
Public Color ChaosColor
{
Get {return chaosColor ;}
Set {chaosColor = value ;}
}
# Endregion
# Region custom background color (white by default)
Color backgroundColor = Color. White;
Public Color BackgroundColor
{
Get {return backgroundColor ;}
Set {backgroundColor = value ;}
}
# Endregion
# Region custom random color array
Color [] colors = {Color. Black, Color. Red, Color. DarkBlue, Color. Green, Color. Orange, Color. Brown, Color. DarkCyan, Color. Purple };
Public Color [] Colors
{
Get {return colors ;}
Set {colors = value ;}
}
# Endregion
# Region Custom font Array
String [] fonts = {"Arial", "Georgia "};
Public string [] Fonts
{
Get {return fonts ;}
Set {fonts = value ;}
}
# Endregion
# Region custom random code string sequence (separated by commas)
String codeSerial = ", a, B, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, h, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z ";
Public string CodeSerial
{
Get {return codeSerial ;}
Set {codeSerial = value ;}
}
# Endregion
# Region generates a waveform filter effect
Private const double PI = 3.1415926535897932384626433832795;
Private const double pi2= 6.283185307179586476925286766559;
/// <Summary>
/// Sine curve Wave Distorted Image
/// </Summary>
/// <Param name = "srcBmp"> image path </param>
/// <Param name = "bXDir"> True for distortion </param>
/// <Param name = "nMultValue"> the amplitude multiple of the waveform. The larger the waveform is, the higher the distortion is. Generally, it is 3. </param>
/// <Param name = "dPhase"> start phase of the waveform, value range: [0-2 * PI) </param>
/// <Returns> </returns>
Public Bitmap TwistImage (Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
{
Bitmap destBmp = new Bitmap (srcBmp. Width, srcBmp. Height );
// Fill the bitmap background in white
System. Drawing. Graphics graph = Graphics. FromImage (destBmp );
Graph. FillRectangle (new SolidBrush (Color. White), 0, 0, destBmp. Width, destBmp. Height );
Graph. Dispose ();
Double dBaseAxisLen = bXDir? (Double) destBmp. Height: (double) destBmp. Width;
For (int I = 0; I <destBmp. Width; I ++)
{
For (int j = 0; j <destBmp. Height; j ++)
{
Double dx = 0;
Dx = bXDir? (PI2 * (double) j)/dBaseAxisLen: (PI2 * (double) I)/dBaseAxisLen;
Dx + = dPhase;
Double dy = Math. Sin (dx );
// Obtain the color of the current vertex
Int nOldX = 0, nOldY = 0;
NOldX = bXDir? I + (int) (dy * dMultValue): I;
NOldY = bXDir? J: j + (int) (dy * dMultValue );
System. Drawing. Color color = srcBmp. GetPixel (I, j );
If (nOldX> = 0 & nOldX <destBmp. Width
& Amp; nOldY & gt; = 0 & amp; nOldY <destBmp. Height)
{
DestBmp. SetPixel (nOldX, nOldY, color );
}
}
}
Return destBmp;
}
# Endregion
# Region generate Verification Code Image
Public Bitmap CreateImageCode (string code)
{
Int fSize = FontSize;
Int fWidth = fSize + Padding;
Int imageWidth = (int) (code. Length * fWidth) + 4 + Padding * 2;
Int imageHeight = fSize * 2 + Padding;
System. Drawing. Bitmap image = new System. Drawing. Bitmap (imageWidth, imageHeight );
Graphics g = Graphics. FromImage (image );
G. Clear (BackgroundColor );
Random rand = new Random ();
// Add random dry points to the background
If (this. Chaos)
{
Pen pen = new Pen (ChaosColor, 0 );
Int c = Length * 10;
For (int I = 0; I <c; I ++)
{
Int x = rand. Next (image. Width );
Int y = rand. Next (image. Height );
G. DrawRectangle (pen, x, y, 1, 1 );
}
}
Int left = 0, top = 0, top1 = 1, top2 = 1;
Int n1 = (imageHeight-FontSize-Padding * 2 );
Int n2 = n1/4;
Top1 = n2;
Top2 = n2 * 2;
Font f;
Brush B;
Int cindex, findex;
// Random font and color Verification Code characters
For (int I = 0; I <code. Length; I ++)
{
Cindex = rand. Next (Colors. Length-1 );
Findex = rand. Next (Fonts. Length-1 );
F = new System. Drawing. Font (Fonts [findex], fSize, System. Drawing. FontStyle. Bold );
B = new System. Drawing. SolidBrush (Colors [cindex]);
If (I % 2 = 1)
{
Top = top2;
}
Else
{
Top = top1;
}
Left = I * fWidth;
G. DrawString (code. Substring (I, 1), f, B, left, top );
}
// Draw a border with Color. Gainsboro
G. DrawRectangle (new Pen (Color. Gainsboro, 0), 0, 0, image. Width-1, image. Height-1 );
G. Dispose ();
// Generate a waveform (Add By 51aspx.com)
Image = TwistImage (image, true, 4, 4 );
Return image;
}
# Endregion
# Region outputs the created image to the page
Public void CreateImageOnPage (string code, HttpContext context)
{
Response. BufferOutput = true; // note
Response. Cache. SetExpires (DateTime. Now. AddMilliseconds (-1); // note
Response. Cache. SetCacheability (HttpCacheability. NoCache); // note
Response. AppendHeader ("Pragma", "No-Cache"); // note
MemoryStream MS = new MemoryStream ();
Bitmap image = this. CreateImageCode (code );
Image. Save (MS, ImageFormat. Jpeg );
Response. ClearContent ();
Response. ContentType = "image/JPEG ";
Response. BinaryWrite (ms. ToArray ());
Response. End ();
Ms. Close ();
MS = null;
Image. Dispose ();
Image = null;
}
# Endregion
# Region generate random escape code
Public string CreateVerifyCode (int codeLen)
{
If (codeLen = 0)
{
CodeLen = Length;
}
String [] arr = CodeSerial. Split (',');
String code = "";
Int randValue =-1;
Random rand = new Random (unchecked (int) DateTime. Now. Ticks ));
For (int I = 0; I <codeLen; I ++)
{
RandValue = rand. Next (0, arr. Length-1 );
Code + = arr [randValue];
}
Return code;
}
Public string CreateVerifyCode ()
{
Return CreateVerifyCode (0 );
}
# Endregion
# Region Another Verification Code style GenerateVerifyImage (int length)
/// <Summary>
/// Output the created image to the page
/// </Summary>
Public void GenerateVerifyImage (int nLen)
{
String validateCode = ""; // The generated Verification Code
Int nBmpWidth = GetImagewidth (nLen );
Int nBmpHeight = GetImageHeight ();
System. Drawing. Bitmap bmp = new System. Drawing. Bitmap (nBmpWidth, nBmpHeight );
// Bend the image
TwistImage (bmp, true, 12, 2 );

// 1. generate random background color
Int nRed, nGreen, nBlue; // ternary background color
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. Fill in the bitmap background
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. Draw interference lines with a color that is slightly darker than the background
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 );
}
// Use the character set, which can be expanded immediately and control the probability of occurrence of Characters
String strCode = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
// 4. cyclically obtain characters and draw
For (int I = 0; I <nLen; I ++)
{
Int x = (I * 13 + rd. Next (3 ));
Int y = rd. Next (4) + 1;
// Determine the font
System. Drawing. Font font = new System. Drawing. Font ("Courier New", // text Font type
12 + rd. Next () % 4, // text font size
System. Drawing. FontStyle. Bold); // text font style
Char c = strCode [rd. Next (strCode. Length)]; // random character acquisition
ValidateCode + = c. ToString ();
// Draw characters
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 );
}
Session ["ValidateCode"] = validateCode;
// Bend the image
TwistImage (bmp, true, 4, 4 );
Response. BufferOutput = true; // note
Response. Cache. SetExpires (DateTime. Now. AddMilliseconds (-1); // note
Response. Cache. SetCacheability (HttpCacheability. NoCache); // note
Response. AppendHeader ("Pragma", "No-Cache"); // note
// 5. Output byte stream
MemoryStream bstream = new MemoryStream ();
Bmp. Save (bstream, ImageFormat. Jpeg );
Response. ClearContent ();
Response. ContentType = "image/JPEG ";
Response. BinaryWrite (bstream. ToArray ());
Response. End ();
Bstream. Close ();
Bstream = null;
Bmp. Dispose ();
Bmp = null;
Graph. Dispose ();
}
/// <Summary>
/// Obtain the image width of the Verification Code
/// </Summary>
/// <Paramname = "validateNumLength"> Verification code length </param>
/// <Returns> </returns>
Public static int GetImagewidth (int validateNumLength)
{
Return (int) (13 * validateNumLength + 5 );
}
/// <Summary>
/// Obtain the height of the Verification Code
/// </Summary>
/// <Returns> </returns>
Public static int GetImageHeight ()
{
Return 25;
}
# Endregion
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.