当直接请求网站中images目录下的.jpg图片时把图片加上水印,然后输出
1、在web.config中设置一个全局应用程序来处理该目录下的请求
<System.Web> <httpHandlers> <add verb= "*" path= "images/*.jpg" type= "WaterMarker" > |
2、创建一个处理水印的类,对应type中的WaterMarker
1 using System; 2 using System.Web; 3 using System.Drawing; 4 5 /// <summary> 6 ///WaterMarker 的摘要说明 7 /// </summary> 8 public class WaterMarker:IHttpHandler 9 { 10 public bool IsReusable 11 { 12 get { return false; } 13 } 14 15 public void ProcessRequest(HttpContext context) 16 { 17 context.Response.ContentType = "image/jpeg"; 18 //获取报文中的路径 19 string rawUrl = context.Request.RawUrl; 20 //原始图片地址 21 string path = context.Request.MapPath(rawUrl); 22 //logo图片的地址 23 string logoPath = context.Request.MapPath("../logo.png"); 24 //添加水印 25 using (Image Img = Image.FromFile(path)) 26 { 27 using (Image logo = Image.FromFile(logoPath)) 28 { //创建画布 29 Graphics g = Graphics.FromImage(Img); 30 //设置logo位置右下角 31 g.DrawImage(logo,Img.Width-logo.Width-10,Img.Height-logo.Height); 32 //输出图片 33 Img.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg); g.Dispose(); 34 } 35 } 36 37 } 38 public WaterMarker() 39 { 40 // 41 //TODO: 在此处添加构造函数逻辑 42 // 43 } 44 }