Image verification codes are common on the Web login interface. The following is a simple example written in C.
1. CreateValidateImage. aspxPage, pay attention to reference the two namespaces System. Drawing and System. Drawing. Imaging.
The Code is as follows:
Public class ValidateImage: System. Web. UI. Page
{
Private void Page_Load (object sender, System. EventArgs e)
{
// Generate the verification code
String validateCode = CreateValidateCode ();
// Generate an image
Bitmap bitmap = new Bitmap (70, 25 );
// Set the background color of the image
SetBgColor (bitmap, Color. Brown );
// Image Rendering interference
DrawDisturb (bitmap );
// Draw the verification code
DrawValidateCode (bitmap, validateCode );
// Save the verification code image and wait for the output
Bitmap. Save (Response. OutputStream, ImageFormat. Gif );
}
// Generate a four-digit verification code for the A-Z
Private string CreateValidateCode ()
{
String validateCode = string. Empty;
Random random = new Random ();
For (int I = 0; I <4; I ++)
{
// N = 1 ~ 26
Int n = random. Next (26 );
ValidateCode + = (char) (n + 65 );
}
// Save the verification code
Session ["ValidateCode"] = validateCode;
Return validateCode;
}
Private void SetBgColor (Bitmap bitmap, Color color)
{
For (int x = 0; x <bitmap. Width; x ++)
{
For (int y = 0; y <bitmap. Height; y ++)
{
Bitmap. SetPixel (x, y, color );
}
}
}
Private void DrawDisturb (Bitmap bitmap)
{
Random random = new Random ();
For (int x = 0; x <bitmap. Width; x ++)
{
For (int y = 0; y <bitmap. Height; y ++)
{
// 50? Set the interference concentration as needed
If (random. Next (100) <= 50)
Bitmap. SetPixel (x, y, Color. White );
}
}
}
Private void DrawValidateCode (Bitmap bitmap, string validateCode)
{
// Obtain the Paster object
Graphics g = Graphics. FromImage (bitmap );
// Set the font for painting
Font font = new Font ("Arial", 14, FontStyle. Bold | FontStyle. Italic );
// Start position of the painting
Int posX = 2;
Int posY = 2;
// Draw the verification code Image
G. DrawString (validateCode, font, Brushes. Black, posX, posY );
}
2.Verification code usage
You can directly use the verification code on the webpage.
The corresponding Session can be obtained from Session ["ValidateCode "].