[C#]簡單實做Captcha (完全用.Net內建函式)

  • 8534
  • 0
  • C#
  • 2011-02-06

摘要:[C#]簡單實做Captcha (完全用.Net內建函式)

看到保哥的這篇實做Captcha,所以我手癢的也自己try了一下,當然主要還是參考保哥的那篇。

01 using (Bitmap bmp = new Bitmap(90, 30))
02 {
03     int x1 = 0;
04     int y1 = 0;
05     int x2 = 0;
06     int y2 = 0;
07     int x3 = 0;
08     int y3 = 0;
09     int intNoiseWidth = 25;
10     int intNoiseHeight = 15;
11     Random rdn = new Random();
12     Graphics g = Graphics.FromImage(bmp);
13
14
    //設定字型
15     Font font = new Font("Courier New", 12, FontStyle.Bold);
16
17
    //設定圖片背景
18     g.Clear(Color.Cornsilk);
19
20
    //產生雜點
21     for (int i = 0; i < 80; i++)
22     {
23         x1 = rdn.Next(0, bmp.Width);
24         y1 = rdn.Next(0, bmp.Height);
25         bmp.SetPixel(x1, y1, Color.Brown);
26     }

27
28
    //產生擾亂弧線
29     for (int i = 0; i < 15; i++)
30     {
31         x1 = rdn.Next(bmp.Width - intNoiseWidth);
32         y1 = rdn.Next(bmp.Height - intNoiseHeight);
33         x2 = rdn.Next(1, intNoiseWidth);
34         y2 = rdn.Next(1, intNoiseHeight);
35         x3 = rdn.Next(0, 45);
36         y3 = rdn.Next(-270, 270);
37         g.DrawArc(new Pen(Brushes.Gray), x1, y1, x2, y2, x3, y3);
38     }

39
40
    //把GenPassword()方法換成你自己的密碼產生器,記得把產生出來的密碼存起來日後才能與user的輸入做比較。
41     g.DrawString(GenPassword(6), font, Brushes.Black, 3, 3);
42
43
    //你可以直接輸出到web page像保哥一樣,我這邊選擇儲存成GIF檔案。
44     bmp.Save(@"C:\Temp\Captcha.gif", ImageFormat.Gif);
45 }

下面是輸出的結果

 

附加參考:輸入資料的,真的是人:Auto-Input Protection for ASP.NET