继承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页面,显示图片,水印就会自动加上了

posted @ 2012-03-10 18:28  ajunfly  阅读(838)  评论(0编辑  收藏  举报