以下為引用的內(nèi)容:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AuthCode
{
[ToolboxData("〈{0}:AuthCode runat=server>〈/{0}:AuthCode>")]
public class AuthCode : WebControl
{
/// 〈summary>
/// 獲得驗證碼的值
/// 〈/summary>
/// 〈returns>驗證碼〈/returns>
public string GetValue()
{
return HttpContext.Current.Session["value"].ToString();
}
[Bindable(true)]
[Category("Appearance")]
[Description("驗證碼字符長度")]
[DefaultValue("ss")]
[Localizable(true)]
//長度
internal static int mySize;
public int MySize
{
get { return AuthCode.mySize; }
set
{
AuthCode.mySize = value;
}
}
public AuthCode()
: base(HtmlTextWriterTag.Img)//重寫父類的構(gòu)造(輸出流的HTML標(biāo)記)
{ }
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);//將要輸出的的HTML標(biāo)簽的屬性和樣式添加到指定的 HtmlTextWriter中
writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");//添加樣式
/**-
* 圖片的onclick事件 "this.src='VerifyImg.jd?id=' Math.random()"
* 每次單擊一次就有一個新的圖片請求路徑(VerifyImg.jd?id=' Math.random())參數(shù)只是
* 告訴瀏覽器這是一個新的請求然后經(jīng)過 IHttpHander處理生成新的圖片 id 沒有任何實(shí)際意思(創(chuàng)造一個新的請求)
* -**/
writer.AddAttribute("onclick", "this.src='img.jd?id=' Math.random()");//添加js VerifyImg.jd
writer.AddAttribute(HtmlTextWriterAttribute.Src, "img.jd");
writer.AddAttribute("alt", "點(diǎn)擊刷新");
}
}
}
3.2--》新建處理類(必須實(shí)現(xiàn) IHttpHandler,IRequiresSessionState 兩個接口)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.SessionState;
using System.Drawing;
using System.IO;
namespace AuthCode
{
public class AuthCodeHttpHander:IHttpHandler,IRequiresSessionState
{
/// 〈summary>
/// 返回驗證碼字符
/// 〈/summary>
/// 〈param name="codeCount">驗證碼長度〈/param>
/// 〈returns>〈/returns>
private string GetRandomNumberString(int codeCount)
{
string strChoice = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strResult = strChoice.Split(new Char[] { ',' });
string strReturn = "";
Random rnd = new Random();
for (int i = 0; i 〈 codeCount; i )
{
int j = rnd.Next(strResult.Length);//隨機(jī)數(shù)不能大于數(shù)組的長度
strReturn = strReturn strResult[j].ToString();
}
return strReturn;
}
private Color GetColor()
{
return Color.Black;
}
private Bitmap CreateImage(string str_AuthCode)
{
/* -----------------------------繪制圖片的樣式 ------------------------------------*/
int width =str_AuthCode.Length* 21;
int height = 30;
Random rad = new Random();
Bitmap bmp = new Bitmap(width, height);
Graphics grp = Graphics.FromImage(bmp);// 在圖片上繪制圖形
grp.Clear(Color.YellowGreen);//填充bmp的背景色
grp.DrawRectangle(new Pen(Color.Red, 1), 0, 0, width - 1, height - 1);//繪制邊框
int num = width * height;
for (int i = 0; i 〈 num; i )//在圖片的指定坐標(biāo)上畫上有顏色的圓點(diǎn)
{
int x = rad.Next(width);
int y = rad.Next(height);
int r = rad.Next(255);
int g = rad.Next(255);
int b = rad.Next(255);
Color c = Color.FromArgb(r, g, b);
bmp.SetPixel(x, y, c);//在圖片的指定坐標(biāo)上畫上有顏色的圓點(diǎn)
}
/*-------------------------- 在圖片繪制字符串------------------------------------ */
Font f = new Font("宋體", 20, FontStyle.Bold);//定義字體
Brush br = new SolidBrush(Color.Black);//定義畫筆的顏色 及字體的顏色
for (int i = 0; i 〈 str_AuthCode.Length; i )
{
string s = str_AuthCode.Substring(i, 1);//單個單個的將字畫到圖片上
Point p = new Point(i * 20 rad.Next(3), rad.Next(3) 1);//字體出現(xiàn)的位置(坐標(biāo))
grp.DrawString(s, f, br, p);//繪制字符串
}
grp.Dispose();
return bmp;//返回
}
/// 〈summary>
/// 是否可以處理遠(yuǎn)程的HTTP請求
/// 〈/summary>
public bool IsReusable
{
get { return true; }
}
/// 〈summary>
/// 將驗證碼圖片發(fā)送給WEB瀏覽器
/// 〈/summary>
/// 〈param name="context">〈/param>
public void ProcessRequest(HttpContext context)
{
int size = AuthCode.mySize; //Int32.Parse((String)context.Session["Size"]);
MemoryStream ms = new MemoryStream(); // 創(chuàng)建內(nèi)存流(初始長度為0 自動擴(kuò)充)
string NumStr = GetRandomNumberString(size);// 獲得驗證碼字符
context.Session.Add("value", NumStr);//將驗證碼字符保存到session里面
Bitmap theBitmap = CreateImage(NumStr);// 獲得驗證碼圖片
theBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//將位圖寫入內(nèi)存流
context.Response.ClearContent(); //清除緩沖區(qū)里的所有內(nèi)容輸出
context.Response.ContentType = "image/jpeg"; //需要輸出圖象信息 要修改HTTP頭
context.Response.BinaryWrite(ms.ToArray()); //將內(nèi)存流寫入HTTP輸出流
theBitmap.Dispose(); //釋放資源
ms.Close();//釋放資源
ms.Dispose();//釋放資源
context.Response.End();
}
}
}
|