模版和處理程序
封面數字水印:運用httphandler技術
封面數字水印的實現:
1.創建一個Ihttphandler的類Handler1
2.在Handler1中寫代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
namespace WebApplication1
{
/// <summary>
/// Handler1 的摘要說明
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//
string path = "~/ProductImgs/";
string a = context.Request.MapPath(path + context.Request.Params["id"].ToString() + ".jpg");
Image m = null;
if (File.Exists(a) )
{
m = Image.FromFile(a);
Graphics g = Graphics.FromImage(m);
g.DrawString("12345", new Font("宋體", 20), Brushes.Red, m.Width - 60, m.Height - 20);
g.Dispose();
}
else
{
m = Image.FromFile(context .Request.MapPath (path ));
}
context.Response.ContentType = "image/jpeg";
m.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
m.Dispose();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
3.修改Default.aspx中圖片的src屬性
<body> <form id="form1" runat="server"> <div> <img alt="" class="style1" src="Handler1.ashx?id=1" /> <img alt="" class="style2" src="Handler1.ashx?id=2" /> <img alt="" class="style1" src="Handler1.ashx?id=3" /> <img alt="" class="style2" src="Handler1.ashx?id=4" /> </div> </form> </body>
運行結果如下:
數字水印的實現(全局方式)
1.修改web.config文件,在文件中添加以下代碼行
<httpHandlers>
<addverb="* "path="ProductImgs/*.jpg" validate="false" type="WebApplication1.Handler1"/>
</httpHandlers>
Path:訪問路徑
Type:指定的處理程序
2.創建一個Ihttphandler的類Handler1
3. Handler1代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
namespace WebApplication1
{
///<summary>
/// Handler1 的摘要說明
///</summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContextcontext)
{
//指定文件夾
stringOL = "~/ProductImgs/default.jpg";
//定義一個圖片
Imageimage = null;
//判斷地址是否存在
if (File.Exists (context.Request.PhysicalPath ))
{
//加載文件
image = Image.FromFile(context.Request.PhysicalPath);
//實例化畫布
Graphicsg = Graphics.FromImage(image );
//在image上會在水印
g.DrawString("hahahhahha", newFont("",20), Brushes.Red, image.Width-120,image.Height-25);
//釋放畫布
g.Dispose();
}
else
{
image = Image.FromFile(context .Request.MapPath(OL));
}
//設置輸出類型爲jpeg圖片
context.Response.ContentType = "image.jpeg";
//將修改的圖片存入文件流
image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
image.Dispose();
context.Response.End();
}
public bool IsReusable
{
get
{
returnfalse;
}
}
}
}