ImageValidator.ashx
<%@ WebHandler Language="C#" Class="ImageValidator" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class ImageValidator : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
// character for validating
string[] code = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
string strRd = string.Empty;
Random random = new Random(unchecked((int)DateTime.Now.Ticks));
Bitmap bmp = new Bitmap(80, 25); // create empty image
Graphics graphic = Graphics.FromImage(bmp);
Font font = new Font("Verdana", 14, FontStyle.Italic);
for (int i = 0; i < 5; i++) // random a validate string
{
strRd += code[random.Next(35)];
}
graphic.Clear(Color.White); //設定背景顏色
for (int i = 1; i <= 10; i++)
{
graphic.DrawLine(GetPen(i), random.Next(80), 0, random.Next(80), 30); // ↘
}
graphic.DrawString(strRd, font, Brushes.Black, 0, 0);
for (int i = 0; i <= 50; i++) //亂數產生霧點,擾亂機器人辨別
{
int RandPixelX = random.Next(0, 80);
int RandPixelY = random.Next(0, 25);
bmp.SetPixel(RandPixelX, RandPixelY, Color.Blue);
}
context.Session["ValidateCode"] = strRd; //將驗證碼存入Session以便稍後進行驗證
//context.Response.Cookies.Add(new HttpCookie("ValidateCode", strRd)); //將驗證碼存入cookie以便稍後進行驗證
bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
}
#region getPen 取得筆刷的設定顏色
protected Pen GetPen(int i)
{
Pen PenLine = new Pen(Brushes.Red, 1);//實體化筆刷並設定顏色、大小(畫X,Y軸用)
switch (i)
{
case 1:
PenLine = new Pen(Brushes.Red, 1);
break;
case 2:
PenLine = new Pen(Brushes.BlueViolet, 1);
break;
case 3:
PenLine = new Pen(Brushes.GreenYellow, 1);
break;
case 4:
PenLine = new Pen(Brushes.Gold, 1);
break;
case 5:
PenLine = new Pen(Brushes.MediumBlue, 1);
break;
case 6:
PenLine = new Pen(Brushes.MintCream, 1);
break;
case 7:
PenLine = new Pen(Brushes.Pink, 1);
break;
case 8:
PenLine = new Pen(Brushes.Purple, 1);
break;
case 9:
PenLine = new Pen(Brushes.HotPink, 1);
break;
case 10:
PenLine = new Pen(Brushes.Chocolate, 1);
break;
} return PenLine;
}
#endregion
public bool IsReusable
{
get
{
return false;
}
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>未命名頁面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="~/ImageValidator.ashx" />
</div>
</form>
</body>
</html>