A Google-like verification code written in. net

Source: Internet
Author: User
Tags random seed

Application in B/S structure developmentProgramThe verification code is often used to prevent malicious operations during login. Similar verification codes are found on the internet, but are nothing more than generating a text image. Here, publish a verification code similar to that used by Google.

Effect

CodeAs follows:

Using system;
Using system. text;
Using system. drawing;
Using system. Drawing. drawing2d;
Using system. Drawing. imaging;

Namespace mirainsoft. validatecode
{
/// <Summary>
/// Verification code processing class
/// </Summary>
Public class validatecodefactory
{
/// <Summary>
/// Select the range array for the font
/// </Summary>
Private string [] fonts = {"Times New Roman", "Georgia", "Arial", "Comic Sans MS "};
/// <Summary>
/// Value range array of the Verification Code
/// </Summary>
Private string [] codescopes = {"0", "1", "2", "3", "4", "5", "6", "7 ", "8", "9 "};
///// <Summary>
//// Color value range array
///// </Summary>
// Private color [] colorscopes = {color. crimson, color. palevioletred, color. mediumvioletred, color. purple, color. darkviolet, color. indigo, color. slateblue, color. darkslateblue, color. mediumblue, color. darkblue, color. slateblue, color. darkcyan, color. gold, color. goldenrod, color. orange, color. orangered, color. red, color. darkred };
/// <Summary>
/// Random Number
/// </Summary>
Private random rand;
/// <Summary>
/// Random Seed
/// </Summary>
Private int randseed;
Private string text;
Private int width;
Private int height;
Private string familyname;
Private bitmap image;

/// <Summary>
/// Display text
/// </Summary>
Public String text
{
Get {return this. Text ;}
}
/// <Summary>
/// Generated bitmap
/// </Summary>
Public bitmap image
{
Get {return this. image ;}
}
/// <Summary>
/// Verification Code width
/// </Summary>
Public int width
{
Get {return this. width ;}
}
/// <Summary>
/// Verification Code height
/// </Summary>
Public int height
{
Get {return this. height ;}
}

///


// verification code processing class
///
/// display text length, randomly generated
/// Verification Code width
/// verification Code height
Public validatecodefactory (INT length, int width, int height)
{< br> This. randseed = 111;
for (INT I = 0; I This. TEXT = string. concat (this. text, codescopes [next (codescopes. length)]);
This. setdimensions (width, height);
This. setfamilyname (this. fonts [next (this. fonts. length)]);
This. generateimage ();
}

///


// verification code processing class
///
/// display text
/// Verification Code width
/// Verification Code height
Public validatecodefactory (string s, int width, int height)
{< br> This. randseed = 111;
This. TEXT = s;
This. setdimensions (width, height);
This. setfamilyname (this. fonts [next (this. fonts. length)]);
This. generateimage ();
}

/// <Summary>
/// Verification code processing class
/// </Summary>
/// <Param name = "S"> display text </param>
/// <Param name = "width"> Verification Code width </param>
/// <Param name = "height"> Verification Code height </param>
/// <Param name = "familyname"> font name </param>
Public validatecodefactory (string S, int width, int height, string familyname)
{
This. randseed = 111;
This. Text = s;
This. setdimensions (width, height );
This. setfamilyname (familyname );
This. generateimage ();
}

/// <Summary>
/// Garbage collection
/// </Summary>
~ Validatecodefactory ()
{
Dispose (false );
}

/// <Summary>
/// Release resources
/// </Summary>
Public void dispose ()
{
GC. suppressfinalize (this );
This. Dispose (true );
}

/// <Summary>
/// Release resources
/// </Summary>
/// <Param name = "disposing"> reclaim or not </param>
Protected virtual void dispose (bool disposing)
{
If (disposing)
// Dispose of the bitmap.
This. image. Dispose ();
}

/// <Summary>
/// Set the width and height of the Verification Code
/// </Summary>
/// <Param name = "width"> Verification Code width </param>
/// <Param name = "height"> Verification Code height </param>
Private void setdimensions (INT width, int height)
{
// Check the width and height.
If (width <= 0)
Throw new argumentoutofrangeexception ("width", width, "argument out of range, must be greater than zero .");
If (height <= 0)
Throw new argumentoutofrangeexception ("height", height, "argument out of range, must be greater than zero .");
This. width = width;
This. Height = height;
}

///


// set the font of the displayed text
///
/// font name
private void setfamilyname (string familyname)
{< br> try
{< br> Font font = new font (this. familyname, 12f);
This. familyname = familyname;
font. dispose ();
}< br> catch
{< br> This. familyname = system. drawing. fontfamily. genericserif. name;
}< BR >}

/// <Summary>
/// Generate the verification code
/// </Summary>
Private void generateimage ()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap (this. Width, this. Height, pixelformat. format32bppargb );

// Create a graphics object for drawing.
Graphics G = graphics. fromimage (Bitmap );
G. smoothingmode = smoothingmode. antialias;
Rectangle rect = new rectangle (0, 0, this. Width, this. Height );

// fill in the background.
hatchbrush = new hatchbrush (hatchstyle. smallconfetti, color. lightgray, color. white);
G. fillrectangle (hatchbrush, rect);

// set up the text font.
sizef size;
float fontsize = rect. height + 1;
Font font;
// adjust the font size until the text fits within the image.
DO
{< br> fontsize --;
font = new font (this. familyname, fontsize, fontstyle. bold);
size = G. measurestring (this. text, font);
}while (size. width/4f) * 3f> rect. width);

// Set up the text format.
Stringformat format = new stringformat ();
Format. Alignment = stringalignment. Center;
Format. linealignment = stringalignment. Center;

// Create a path using the text and warp it randomly.
Graphicspath Path = new graphicspath ();
Path. addstring (this. Text, Font. fontfamily, (INT) font. style, Font. Size, rect, format );
Float v = 4f;
Pointf [] points =
{
New pointf (next (rect. width)/V, next (rect. Height)/V ),
New pointf (rect. Width-next (rect. width)/V, next (rect. Height)/V ),
New pointf (next (rect. width)/V, rect. Height-next (rect. Height)/V ),
New pointf (rect. Width-next (rect. width)/V, rect. Height-next (rect. Height)/V)
};
Matrix matrix = new matrix ();
Matrix. Translate (0f, 0f );
Path. Warp (points, rect, matrix, warpmode. Perspective, 0f );

// Draw the text.
Hatchbrush = new hatchbrush (hatchstyle. largeconfetti, color. Gray, color. Gray );
G. fillpath (hatchbrush, PATH );

// Add some random noise.
Int M = math. Max (rect. Width, rect. Height );
For (INT I = 0; I <(INT) (rect. Width * rect. Height/30f); I ++)
{
Int x = next (rect. width );
Int y = next (rect. Height );
Int W = next (M/50 );
Int H = next (M/50 );
G. fillellipse (hatchbrush, X, Y, W, H );
}

// Clean up.
Font. Dispose ();
Hatchbrush. Dispose ();
G. Dispose ();

// Set the image.
This. Image = bitmap;
}

/// <Summary>
/// Obtain a random number
/// </Summary>
/// <Returns> int </returns>
Private int next ()
{
Rand = new random (unchecked (INT) datetime. Now. ticks) * randseed ++ );

Return Rand. Next ();
}
/// <Summary>
/// Obtain a random number
/// </Summary>
/// <Param name = "maxvalue"> upper bound of a random number </param>
/// <Returns> int </returns>
Private int next (INT maxvalue)
{
Rand = new random (unchecked (INT) datetime. Now. ticks) * Next ());

Return Rand. Next (maxvalue );
}

/// <Summary>
/// Obtain a random number
/// </Summary>
/// <Param name = "minvalue"> lower bound to a random number </param>
/// <Param name = "maxvalue"> upper bound of a random number </param>
/// <Returns> int </returns>
Private int next (INT minvalue, int maxvalue)
{
Rand = new random (unchecked (INT) datetime. Now. ticks) * Next ());

Return Rand. Next (minvalue, maxvalue );
}
}
}

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.