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

  1. 添加一个类并实现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), 00, 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;
            }
        }
    }
  2. 配置web.config文件:
    在 <httpHandlers>节点中添加一下代码:
     <add verb="*" path="Images/*.jpg" type="waterH"/><!--path为图片放置路径,type为新添加的实现IHttpHandler接口的类名称-->
  3. 配置IIS:如图
posted @ 2010-12-08 14:28  凭栏处  阅读(873)  评论(1编辑  收藏  举报