隨即繪製驗證碼圖像

 

  1. protected void Page_Load(object sender, EventArgs e)  
  2.  {  
  3.      Bitmap bmp = new Bitmap(80, 40);//定義一個畫布  
  4.      Graphics g = Graphics.FromImage(bmp);  
  5.      g.Clear(Color.White);  
  6.      g.DrawRectangle(Pens.Black, 0, 0, 79, 39);//繪製邊框  
  7.      //定義七種顏色  
  8.      Color[] colors = { Color.Black, Color.Red, Color.Blue, Color.DarkGreen, Color.Purple, Color.DarkGoldenrod, Color.Chocolate };  
  9.      //定義七種字體  
  10.      string[] fontNames = { "宋體""楷體_GB2312""隸書""Arial""Comic Sans MS""Microsoft Sans Serif""Times New Roman" };  
  11.      //隨機數  
  12.      Random rand = new Random();  
  13.      //隨機生成驗證字符  
  14.      char[] chs = new char[] { (char)(65 + rand.Next(26)), (char)(65 + rand.Next(26)), (char)(65 + rand.Next(26)) };  
  15.      Brush brush;//定義畫刷  
  16.      Font font;//定義字體  
  17.      int x, y;//座標  
  18.      for (int i = 0; i < 3; i++)  
  19.      {  
  20.          brush = new SolidBrush(colors[rand.Next(7)]);  
  21.          font = new Font(fontNames[rand.Next(7)], 18, FontStyle.Bold);  
  22.          x = i * 20 + 2;  
  23.          y = 5 + rand.Next(5);  
  24.          g.RotateTransform(rand.Next(-10, 9));  
  25.          //畫出字符  
  26.          g.DrawString(chs[i].ToString(), font, brush, x, y);  
  27.      }  
  28.  
  29.      Pen[] pens = { Pens.Gray, Pens.LightGray };  
  30.      for (int i = 0; i < 200; i++)//繪製隨機躁點  
  31.      {  
  32.          x = rand.Next(bmp.Width - 1);  
  33.          y = rand.Next(bmp.Height - 1);  
  34.          g.DrawEllipse(pens[i % 2], x, y, 1, 1);  
  35.      }  
  36.  
  37.      MemoryStream ms = new MemoryStream();  
  38.      bmp.Save(ms, ImageFormat.Jpeg);  
  39.      this.Response.Clear();  
  40.      this.Response.ContentType = "p_w_picpath/Jpeg";  
  41.      this.Response.BinaryWrite(ms.ToArray());//輸出圖像  
  42.      g.Dispose();  
  43.      bmp.Dispose();  
  44.  } 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章