一般處理程序WaterMark.ashx的代碼:
<%@ WebHandler Language="C#" Class="WaterMark" %>
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.SessionState;
public class WaterMark : IHttpHandler, IRequiresSessionState // 要使用session必須實現該接口,記得要導入System.Web.SessionState命名空間
{
public void ProcessRequest(HttpContext context)
{
string checkCode = GenCode(5); // 產生5位隨機字符
context.Session["Code"] = checkCode; //將字符串保存到Session中,以便需要時進行驗證
System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成隨機生成器
Random random = new Random();
//清空圖片背景色
g.Clear(Color.White);
// 畫圖片的背景噪音線
int i;
for (i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);
g.DrawString(checkCode, font, brush, 2, 2);
//畫圖片的前景噪音點
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
/// <summary>
/// 產生隨機字符串
/// </summary>
/// <param name="num">隨機出幾個字符</param>
/// <returns>隨機出的字符串</returns>
private string GenCode(int num)
{
string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//"的一是在不了有和人這中大為上個國我以要他時來用們生到作地于出就分對成會可主發年動同工也能下過子說產種面而方后多定行學法所民得經十三之進著等部度家電力里如水化高自二理起小物現實加量都兩體制機當使點從業本去把性好應開它合還因由其些然前外天政四日那社義事平形相全表間樣與關各重新線內數正心反你明看原又么利比或但質氣第向道命此變條只沒結解問意建月公無系軍很情者最立代想已通并提直題黨程展五果料象員革位入常文總次品式活設及管特件長求老頭基資邊流路級少圖山統接知較將組見計別她手角期根論運農指幾九區強放決西被干做必戰先回則任取據處隊南給色光門即保治北造百規熱領七海口東導器壓志世金增爭濟階油思術極交受聯什認六共權收證改清己美再采轉更單風切打白教速花帶安場身車例真務具萬每目至達走積示議聲報斗完類八離華名確才科張信馬節話米整空元況今集溫傳土許步群廣石記需段研界拉林律叫且究觀越織裝影算低持音眾書布復容兒須際商非驗連斷深難近礦千周委素技備半辦青省列習響約支般史感勞便團往酸歷市克何除消構府稱太準精值號率族維劃選標寫存候毛親快效斯院查江型眼王按格養易置派層片始卻專狀育廠京識適屬圓包火住調滿縣局照參紅細引聽該鐵價嚴";
char[] chastr = str.ToCharArray();
// string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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", "#", "$", "%", "&", "@" };
string code = "";
Random rd = new Random();
int i;
for (i = 0; i < num; i++)
{
//code += source[rd.Next(0, source.Length)];
code += str.Substring(rd.Next(0, str.Length), 1);
}
return code;
}
public bool IsReusable
{
get
{
return false;
}
}
}
應用到文件中點擊刷新
<script type="text/javascript">
function changeCode() {
var imgNode = document.getElementById("vimg");
imgNode.src = "handler/WaterMark.ashx?t=" + (new Date()).valueOf(); // 這里加個時間的參數是為了防止瀏覽器緩存的問題
}
</script>
</head>
<body>
<img src="WaterMark.ashx" id="vimg" alt="" /><input type="button" value="換一張圖片" onclick="changeCode()" />
</body>
</html>
.NET在后置代碼中輸入JS提示語句(背景不會變白)
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('加入暫存架成功!');</script>");