本文實例講述了asp.net繼承IHttpHandler接口實現給網站圖片添加水印功能。分享給大家供大家參考,具體如下:
先展示圖片效果:

1. 在App_Code下添加類文件,命名為ImageSY 文件內容如下
public class ImageSY : IHttpHandler
{
public ImageSY()
{
//
//TODO: 在此處添加構造函數邏輯
//
}
#region IHttpHandler 成員
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
//獲得請求的物理圖片路徑
string imagePath = context.Request.PhysicalPath;
System.Drawing.Image image = null;
if (File.Exists(imagePath))
{
//定義水印文字
string text = "本圖片來至我的網站";
//定義水印文字字體大小
int fontSize = 22;
//水印文字字體
Font font = new Font("宋體", fontSize);
//根據圖片物理地址加載圖片
image = System.Drawing.Image.FromFile(imagePath);
Graphics g = Graphics.FromImage(image);
//獲取要繪制水印文字所需要的顯示區域大小
SizeF size = g.MeasureString(text, font);
if (size.Width > image.Width || size.Height > image.Height)
{
}
else
{
Brush brush = Brushes.Red;
g.DrawString(text, font, brush, image.Width - size.Width, image.Height - size.Height);
g.Dispose();
}
}
else
{
}
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
#endregion
}
2. 配置WebConfig,添加Location新節點
<location path="images"> <system.web> <httpHandlers> <!---對jpg文件添加水印--> <add verb="*" type="ImageSY" path="*.jpg"/> <add verb="*" type="ImageSY" path="*.gif"/> <add verb="*" type="ImageSY" path="*.bmp"/> </httpHandlers> </system.web> </location>
3. 測試,新建aspx頁面,顯示圖片,水印就會自動加上了
更多關於asp.net相關內容感興趣的讀者可查看本站專題:《asp.net操作json技巧總結》、《asp.net字符串操作技巧匯總》、《asp.net操作XML技巧總結》、《asp.net文件操作技巧匯總》、《asp.net ajax技巧總結專題》及《asp.net緩存操作技巧總結》。
希望本文所述對大家asp.net程序設計有所幫助。