asp. net creates bitmaps to generate validation images class of captchas class

  • 2020-09-28 08:51:40
  • OfStack

Code:


public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
// Creates a bitmap and gives the width and height of the specified border 
using (Image img=new Bitmap(80,25))
{
// Create painter objects in img Object draw string 
using (Graphics g=Graphics.FromImage(img))
{ 
// Sets the background color of the bitmap. The default color is black 
g.Clear(Color.White);
// Sets the width and height of the captcha , img.Width-1, img.Height-1 The background color mainly covers the border line 
g.DrawRectangle(Pens.Black, 0, 0, img.Width-1, img.Height-1);
// the 100 Noise points, transfer painter objects, bitmap objects 
DrawPoint(100, g, img);
// draw 4 A string of captchas 
string vcode=GetCode(4);//vcode I can assign a value to Cookie
g.DrawString(vcode,
new Font("Arial", 14, FontStyle.Strikeout | FontStyle.Strikeout), // FontStyle Font styles, multiple styles, required | line  
Brushes.Black,
new RectangleF(r.Next(20), r.Next(7), img.Width, img.Height));
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);// Save the captcha object, specifying yes Jpeg format 
}
}
}
// Method of drawing noise points 
void DrawPoint(int point,Graphics g,Image img)
{
for (int i = 0; i < point; i++)
{
int x = r.Next(img.Width);
int y = r.Next(img.Width);
g.DrawLine(Pens.Red,
new Point(x, y),
new Point(x+2, y+2));
}
}
// The random number 
Random r = new Random();
// Draw the characters 
string GetCode(int point)
{
string txtStr = "ASF2345WE5R9F3HMBCZ455K";// Here, string The string will be converted to  char Arrays, Arabic numerals 1 And lowercase letters l Better not write it in there. It'll make a mess. 
char[] charArr = txtStr.ToArray();
int num = 0;
string code = "";
for (int i = 0; i <point; i++)
{
num = r.Next(charArr.Length);
code +=charArr[num];
}
return code;
}


Related articles: