簡易的Captcha
public class Captcha : IHttpHandler,System.Web.SessionState.IRequiresSessionState {
public void ProcessRequest(HttpContext context)
{
var captcha = new Random((int)DateTime.Now.Ticks).Next(9999).ToString("0000");
var b = CreateCaptcha(captcha);
context.Session.Add("captcha", captcha);
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(b);
}
public bool IsReusable {
get {
return false;
}
}
private byte[] CreateCaptcha(string captcha)
{
using (var ms = new MemoryStream())
{
// 設定驗證圖形長 & 寬
const int captchaWidth = 56, captchaHeight = 20;
var bitmap = new Bitmap(captchaWidth, captchaHeight);
// 設定繪圖區塊
var graphics = Graphics.FromImage(bitmap);
// 設定字型
var fontFamily = new Font("Arial", 14, FontStyle.Italic);
// 設定區塊底色
graphics.Clear(Color.White);
// 繪字
graphics.DrawString(captcha, fontFamily, Brushes.Black, 0, 0);
// 加入雜訊
var random = new Random((int)DateTime.Now.Ticks);
for (var i = 0; i < 200; i++)
{
var randPixelX = random.Next(0, captchaWidth);
var randPixelY = random.Next(0, captchaHeight);
bitmap.SetPixel(randPixelX, randPixelY, Color.Black);
}
// 寫入資料流
bitmap.Save(ms, ImageFormat.Png);
var b = ms.GetBuffer();
return b;
}
}
}
1.此為泛型處理函式(Captcha Ashx),而再用<img src="Captcha .ashx" alt="">即可產生
2.繼承/實作 System.Web.SessionState.IRequiresSessionState 表示此Ashx可以存取Session (因為要將隨機產生的字碼存Session)
3.如果是MVC可以直接在Controller設一個Action負責Captcha,用FileResult傳回圖片 TempData回傳隨機字碼