最近写的一个验证码.

<%@ Import Namespace="System.Web"%>
<%@ Import Namespace="System.Drawing"%>
<%@ Import Namespace="System.Drawing.Drawing2D"%>
<script runat="server" language="c#">
void Page_Load(Object Src, EventArgs E)
{
    CreateCheckCodeImage();
}


private string GenerateCheckCode()
{
    
int number;
    
char code;
    
string checkCode = String.Empty;
    System.Random random 
= new Random();
    
int count = 4;//random.Next(3,6);
    for(int i=0; i<count; i++)
    
{
        number 
= random.Next();
        
if(number % 2 == 0)
            code 
= (char)('0' + (char)(number % 10));
        
else
            code 
= (char)('A' + (char)(number % 26));
        checkCode 
+= code.ToString();
    }

    Session[
"CheckCode"]=checkCode;
    
return checkCode;
}

 
private static Font[] fonts = new Font[]{
    
new System.Drawing.Font("Arial"20, System.Drawing.FontStyle.Regular),
     
new System.Drawing.Font("Arial"24, System.Drawing.FontStyle.Italic),
      
new System.Drawing.Font("Batang",20,System.Drawing.FontStyle.Regular),
    
new System.Drawing.Font("Batang",26,System.Drawing.FontStyle.Italic),
    
new System.Drawing.Font("Courier",28,System.Drawing.FontStyle.Regular),
     
new System.Drawing.Font("Courier",26,System.Drawing.FontStyle.Italic),
    
new System.Drawing.Font("Arial",20,System.Drawing.FontStyle.Bold)
}
;
private static Brush[] brushs = new Brush[]{
    
//new HatchBrush(HatchStyle.Percent30, color, Color.White),
    new HatchBrush(HatchStyle.Percent40, color, Color.White),
    
//new HatchBrush(HatchStyle.Percent25, color, Color.White),
    
//new HatchBrush(HatchStyle.SmallCheckerBoard, color, Color.White)
}
;
private static Color color = Color.Black;
private void CreateCheckCodeImage()
{
  
string codeStr = GenerateCheckCode();
  
int height = 40;
  
  
int witdh = 30 * codeStr.Length;
  Bitmap image 
= new Bitmap(witdh, height);
  Graphics g 
= Graphics.FromImage(image);
  Random rnd 
= new Random();
  Brush brush 
= brushs[rnd.Next(brushs.Length)];
  g.FillRectangle(brush, 
00, witdh, height);
  Font font 
= new System.Drawing.Font("Arial"24, System.Drawing.FontStyle.Regular);
  LinearGradientBrush b 
= new LinearGradientBrush(new Point(00), new Point(40100), color,color);
  
  
for (int i = 0; i < codeStr.Length; i++)
  
{
      Point p 
= new Point(i * 25 + rnd.Next(-35), rnd.Next(-35));
      g.DrawString(codeStr[i].ToString(), fonts[rnd.Next(fonts.Length)], b, p);
  }

  System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
  image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  Response.ClearContent();
  Response.ContentType 
= "image/Gif";
  Response.BinaryWrite(ms.ToArray());
}

</script>
风云
原文地址:https://www.cnblogs.com/lovebanyi/p/657074.html