制作水印图片
1、创建一个“一般处理程序”,命名waterImage
View Code
1 <%@ WebHandler Language="C#" Class="waterImag" %> 2 3 using System; 4 using System.Web; 5 using System.Drawing; 6 7 public class waterImag : IHttpHandler { 8 9 public void ProcessRequest (HttpContext context) { 10 context.Response.ContentType = "image/jpeg";//设置响应头数据类型(给浏览器看) 11 //从地址栏获得要访问的图片的名称 12 string imgName = context.Request.QueryString["imgName"]; 13 //获得图片在服务器上的物理路径 14 string imgPath = context.Server.MapPath("Upload\\"+imgName); 15 //根据物理路径读取图片到内存 16 using (Image img = Image.FromFile(imgPath)) 17 { 18 //获得水印图片的物理路径 19 string waterpath = context.Server.MapPath("baidu.jpg"); 20 //根据物理路径读取水印图片到内存中 21 using (Image wimg = Image.FromFile(waterpath)) 22 { 23 //创建一个“画家”对象,告诉他在img图片上作画 24 using (Graphics g = Graphics.FromImage(img)) 25 { 26 g.DrawImage(wimg, 0, 0);//从左上角开始将水印图片wimg画到img上 27 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //输出到响应流 28 } 29 } 30 } 31 32 } 33 34 public bool IsReusable { 35 get { 36 return false; 37 } 38 } 39 40 }
2、添加一个HTML文件<从这里发出请求>
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <title></title> 6 </head> 7 <body> 8 <img src="waterImag.ashx?ImgName=1.jpg" alt=1 /> 9 </body> 10 </html>
3、添加水印图片(baidu.jpg)到当前网站目录
4、添加另一张要被加水印的图片(1.jpg)
注:缩放水印图片,可使用Bitmap的SetResolution方法;
1 <%@ WebHandler Language="C#" Class="waterImag" %> 2 3 using System; 4 using System.Web; 5 using System.Drawing; 6 7 public class waterImag : IHttpHandler { 8 9 public void ProcessRequest (HttpContext context) { 10 context.Response.ContentType = "image/jpeg";//设置响应头数据类型(给浏览器看) 11 //从地址栏获得要访问的图片的名称 12 string imgName = context.Request.QueryString["imgName"]; 13 //获得图片在服务器上的物理路径 14 string imgPath = context.Server.MapPath("Upload\\"+imgName); 15 //根据物理路径读取图片到内存 16 using (Bitmap img = (Bitmap)Image.FromFile(imgPath)) 17 { 18 //获得水印图片的物理路径 19 string waterpath = context.Server.MapPath("baidu.jpg"); 20 img.SetResolution(400,100);//设置图片的宽高像素 21 //根据物理路径读取水印图片到内存中 22 using (Image wimg = Image.FromFile(waterpath)) 23 { 24 //创建一个“画家”对象,告诉他在img图片上作画 25 using (Graphics g = Graphics.FromImage(img)) 26 { 27 g.DrawImage(wimg, 0, 0);//从左上角开始将水印图片wimg画到img上 28 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //输出到响应流 29 } 30 } 31 } 32 33 } 34 35 public bool IsReusable { 36 get { 37 return false; 38 } 39 } 40 41 }

浙公网安备 33010602011771号