您的位置:首页 > 理论基础 > 计算机网络

asp.net通过实现IHttpHandler接口方法给图片添加水印图片(动态添加,不破坏原图片,但是耗资源)

2010-12-08 14:28 1076 查看
添加一个类并实现IHttpHandler接口,类中需添加System.IO引用(类代码如下)
代码

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Drawing;
using System.IO;
/// <summary>
///waterH 的摘要说明
/// </summary>
public class waterH:IHttpHandler
{
public waterH()
{}
private const string WATERMARK_URL = "~/Images/Watermark.png";
private const string DEFAULTIMAGE_URL = "~/images/blank.gif";
public void ProcessRequest(HttpContext context)
{
System.Drawing.Image Cover;
if (File.Exists(context.Request.PhysicalPath))
{
Cover = Image.FromFile(context.Request.PhysicalPath);
Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
Graphics g = Graphics.FromImage(Cover);
g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
g.Dispose();
watermark.Dispose();
}
else
{
Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
}
context.Response.ContentType = "images/jpeg";
Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}

public bool IsReusable
{
get
{
return false;
}
}
}
配置web.config文件:
在 <httpHandlers>节点中添加一下代码:
<add verb="*" path="Images/*.jpg" type="waterH"/><!--path为图片放置路径,type为新添加的实现IHttpHandler接口的类名称-->
配置IIS:如图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: