继承IHttpHandler实现全局图片水印

转自:http://www.myexception.cn/asp-dotnet/1589884_2.html

继承IHttpHandler实现全局图片水印

本帖最后由 butterfly_onfly 于 2014-03-10 23:29:51 编辑
创建了一个
ImageHandler类库,创建了个namespace ImageHandler
{
    public class WriteHandler:IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
          
            //获取图片路径
            string imgpath = context.Request.PhysicalPath;
            //获取水印图片路径
            string wpath = context.Server.MapPath("~/img/logo.jpg");
            //获取默认图片路径
            string dpath = context.Server.MapPath("~/img/noPicture.jpg");
            Image img;
            if (File.Exists(imgpath))//判断图片是否存在
            {
                img = Image.FromFile(imgpath);//加载图片
                Image wimg = Image.FromFile(wpath);//加载水印图片
                Graphics g = Graphics.FromImage(img);//让显示的图片设置为背景图片
                //绘制显示图片的矩形
                Rectangle re = new Rectangle(img.Width - wimg.Width, img.Height - wimg.Height, wimg.Width, wimg.Height);
                //绘制水印图片的矩形
                Rectangle re1 = new Rectangle(0, 0, wimg.Width, wimg.Height);
                g.DrawImage(wimg, re, re1, GraphicsUnit.Pixel);
                //文字水印
                //LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, wimg.Width, wimg.Height), Color.White, Color.WhiteSmoke, 1.3f, true);
                //g.DrawString("神农蜂语", new Font("楷书", 15), brush, img.Width - wimg.Width, img.Height - wimg.Height);
                g.Dispose();
                wimg.Dispose();
            }
            else
            {
                img = Image.FromFile(dpath);//如果图片不存在,则加载默认图片
            }
            //保存
            img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            img.Dispose();
        }
    }
}
在web应用程序的web.config里面的配置
<system.web>
        <compilation debug="true" targetFramework="4.0" />
      <httpHandlers>
        <add verb="*" path="img/*.jpg" type="ImageHandler"/>
      </httpHandlers>
    </system.web>
但是浏览页面,报错:

在应用程序里面要怎么配置web.config?

------解决方案--------------------
<system.web>

        <compilation debug="true" targetFramework="4.0" />

      <httpHandlers> 
        <add verb="*" path="img/*.jpg" type="ImageHandler.WriteHandler"/>
      </httpHandlers>
</system.web>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值