[C#] 第一次自己作 Captcha(驗證碼) 就上手(1)
2013-03-10
大家註冊的時候會不會發現很多網站都有自己的防止機器人驗證器..
包含Google 也有作出這種元件讓大家使用.. Google Captcha
Google 的
看一下Wiki 定義
全自動區分計算機和人類的圖靈測試(英語:Completely Automated Public Turing test to tell Computers and Humans Apart,簡稱CAPTCHA),俗稱驗證碼,是一種區分用戶是計算機和人的公共全自動程序。在CAPTCHA測試中,作為伺服器的計算機會自動生成一個問題由用戶來解答。這個問題可以由計算機生成並評判,但是必須只有人類才能解答。由於計算機無法解答CAPTCHA的問題,所以回答出問題的用戶就可以被認為是人類。
簡單的說我們要如何讓機器人看不出出來我們合成的字
首先我們先去找一張背景圖 最好跟你想要合成的文字是相似的最好
我在網路上面找到這張圖片
圖片來源 : http://een.se/niklas/sis/index.html
之後我們可以在上面隨便的找一個點,之後把文字寫上去 ..
/// <summary>/// 製作Captcha/// </summary>/// <param name="text">文字</param>/// <param name="fontName">字體名稱</param>/// <param name="backgroundImagePath">採樣的背景圖</param>/// <param name="width">結果的圖片寬度</param>/// <param name="height">結果的圖片高度</param>/// <returns></returns>public Bitmap GetCaptcha(string text, string fontName, string backgroundImagePath, int width, int height)
{ var backImage = new Bitmap(backgroundImagePath); //如果原圖過小 就以原圖大小為主 if (backImage.Width < width || backImage.Height < height) {throw new Exception("結果尺寸不得小於採樣大小的圖片");
}
//隨機取一個位置 並且按造欲需求的大小裁切 //請注意隨機採樣範圍 記得為 圖片寬度-欲取的寬度 高度也是 ,不然會發生裁切超過範圍backImage =
backImage.Clone(
new Rectangle(new Random().Next(0, backImage.Width - width),
new Random().Next(0, backImage.Height - height), width, height), backImage.PixelFormat);Graphics graphics = Graphics.FromImage(backImage);
//合成的文字為黑色 Brush br = new SolidBrush(Color.Black); //將字體畫上圖片 //字體的大小 為 寬度/字數graphics.DrawString(text, new Font(new FontFamily(fontName), (float)width / (text.Length)), br, new PointF(0, 0));
return backImage;}
結果:
Helper helper=new Helper();var result=helper.GetCaptcha("ABCDEFG", "Arial", Server.MapPath("bk.jpg"), 150,50);
Helper helper=new Helper();var result=helper.GetCaptcha("WXYZ", "Arial", Server.MapPath("bk.jpg"), 100,40);
Helper helper=new Helper();var result=helper.GetCaptcha("WXYZ", "微軟正黑體", Server.MapPath("bk.jpg"), 100,40);
