2008年9月12日 星期五

如何產生辨識圖形(9.12)

現在有很多網頁,它們都會有個圖形驗證的功能。
有時候可能會出現在加入會員,
有時候可能會出現在發表問題、論壇等,
主要就是防止別人使用「程式」來胡作非為,
畢竟,加了一個圖形驗證,是用肉眼來辨識的,
「程式」要突破,就比較難了~~~(或許根本沒法做到)。
那現在,我們來看看這功能是如何達成的。


要產生如此的畫面,建議使用二個網頁,
一個是主畫面,另一個是負責畫圖的。
以下採用
「Default.aspx」:主畫面
「Default2.aspx」:畫圖的網頁
來制作

程式碼 Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;//畫圖相關的類別


public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

//產生圖形

BindIMG();

}

}

#region 產生圖形

private void BindIMG()
{

//定義圖形大小、圖形解析度
Bitmap BMP = new Bitmap(300, 100,System.Drawing.Imaging.PixelFormat.Format24bppRgb );

Graphics formGraphics = Graphics.FromImage(BMP);

//內填滿

formGraphics.FillRectangle(new SolidBrush(Color.PaleGoldenrod
), 0, 0, 300, 100);

string drawString = "";

//用亂數取六位數

Random rnd = new Random();

for (int i = 0; i < 6; i++)
{

drawString += string.Format("{0} ", rnd.Next(9));//產生小於10的整數

}



//定義字型,大小

Font drawFont = new Font("Comic Sans MS", 32);

//定義筆刷顏色

SolidBrush drawBrush = new SolidBrush(Color.YellowGreen
);

//座標位置

Single x = 20;
Single y = 15;

//畫出內容

formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);

//釋出資源
drawFont.Dispose();
drawBrush.Dispose();
formGraphics.Dispose();


//將繪圖相關存到session,在另一個網頁拿來用


Session["BMP"] = BMP;

//由另一個網頁輸出

Image1.ImageUrl = "Default2.aspx";


}
#endregion

}



程式碼 Default2.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;


public partial class Default2 : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
//利用剛剛存到session的圖片讀出
Bitmap BMP = (Bitmap)Session["BMP"];
MemoryStream tempStream = new
MemoryStream();
//將圖片存到記憶體
BMP.Save(tempStream,System.Drawing.Imaging.ImageFormat.Png);

Response.ClearContent();
Response.ContentType = "image/png";
Response.BinaryWrite(tempStream.ToArray());//將圖片用二進位輸出
Response.End();

}

}



由於圖片是根據我們製作的「drawString」字串畫出來的,
接下來若要判斷的話,我們則使用它來比對使用者輸入的文字即可。