Verification code and byte [] images produced in the background, codebyte
Reference namespace
Using System. Drawing;
Using System. Drawing. Drawing2D;
Using System. Drawing. Imaging;
Using System. IO;
Generation Method
/// <Summary> Generate the verification code
/// </Summary>
/// <Returns> </returns>
Public string GetCheckCode ()
{
Int number;
Char code;
String checkCode = String. Empty;
System. Random random = new Random ();
Do
{
Number = random. Next ();
If (number % 2 = 0)
Code = (char) ('0' + (char) (number % 10 ));
Else
Code = (char) ('A' + (char) (number % 26 ));
If (code = 'O' | code = 'O') continue;
CheckCode + = code. ToString ();
} While (checkCode. Length <4 );
// Code is stored in session
Kmhcs. Infrastructure. SessionHelper. SetSession ("checkCode", checkCode. ToUpper ());
Byte [] bytes = CreateValidateGraphic (checkCode. ToLower ());
Var response = new BaseResponse <string> ();
Var src = "data: image/jpeg; base64," + Convert. ToBase64String (bytes); // Convert the HTML Tag img to display it directly
Return src;
}
/// <Summary>
/// Image of the Verification Code
/// </Summary>
/// <Param name = "containsPage"> </param>
/// <Param name = "validateNum"> </param>
Public static byte [] CreateValidateGraphic (string checkCode)
{
Bitmap image = new Bitmap (int) Math. Ceiling (checkCode. Length * 13.5), 22 );
Graphics g = Graphics. FromImage (image );
Try
{
// Generate a random Generator
Random random = new Random ();
// Clear the background color of the image
G. Clear (Color. White );
// Picture interference line
For (int I = 0; I <25; I ++)
{
Int x1 = random. Next (image. Width); int x2 = random. Next (image. Width );
Int y1 = random. Next (image. Height );
Int y2 = random. Next (image. Height );
G. DrawLine (new Pen (Color. Silver), x1, y1, x2, y2 );
}
Font font = new Font ("Arial", 12, (FontStyle. Bold | FontStyle. Italic ));
LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. Width, image. Height ),
Color. Blue, Color. DarkRed, 1.2f, true); g. DrawString (checkCode, font, brush, 3, 2 );
// Foreground interference points
For (int I = 0; I <100; I ++)
{
Int x = random. Next (image. Width); int y = random. Next (image. Height );
Image. SetPixel (x, y, Color. FromArgb (random. Next ()));
}
// Draw the border line of the image
G. DrawRectangle (new Pen (Color. Silver), 0, 0, image. Width-1, image. Height-1 );
// Save image data
MemoryStream stream = new MemoryStream ();
Image. Save (stream, ImageFormat. Jpeg );
// Output image
Return stream. ToArray ();
}
Finally
{
G. Dispose ();
Image. Dispose ();
}
}