创建一个一般处理程序:
一般处理程序代码:
1 <%@ WebHandler Language="C#" Class="ImgWaterMark" %> 2 using System; 3 using System.Web; 4 //先导入两个命名空间 5 using System.Drawing; 6 using System.Drawing.Imaging; 7 8 public class ImgWaterMark03 : IHttpHandler 9 { 10 public void ProcessRequest(HttpContext context) 11 { 12 context.Response.ContentType = "image/jpeg";//图片格式 13 string imgFile = context.Server.MapPath("Image/01.jpg");//原图路径 14 string waterFile = context.Server.MapPath("Image/02.png");//水印图片路径 15 using (Image img = Image.FromFile(imgFile))//原图片 16 { 17 using (Bitmap map = new Bitmap(img.Width, img.Height))//创建一张位图,画板 18 { 19 using (Graphics gh = Graphics.FromImage(map))//为画板创建一个画笔 20 { 21 using (Image waterImg = Image.FromFile(waterFile))//水印图片 22 { 23 gh.DrawImage(img, new Point(0, 0));//将图片画在画板上 24 //在原图上绘制水印图片(右下角) 25 gh.DrawImage(waterImg, new Rectangle(
img.Width - waterImg.Width - 15,
img.Height - waterImg.Height - 10,
waterImg.Width, waterImg.Height),
0, 0, waterImg.Width, waterImg.Height,
GraphicsUnit.Pixel, SetAttributes(60)
); 26 //以输入流的方式将图片输出到浏览器端 27 map.Save(context.Response.OutputStream, ImageFormat.Jpeg); 28 } 29 } 30 } 31 } 32 } 33 //设置水印图片的透明度 34 protected ImageAttributes SetAttributes(float values) 35 { 36 float[][] attributes = { 37 new float[]{1,0,0,0,0}, 38 new float[]{0,1,0,0,0}, 39 new float[]{0,0,1,0,0}, 40 new float[]{0,0,0,values/100f,0}, 41 new float[]{0,0,0,0,1} 42 }; 43 ColorMatrix colMatrix = new ColorMatrix(attributes);//颜色矩阵 44 ImageAttributes imgAttributes = new ImageAttributes();//创建设置颜色矩阵对象 45 //调整颜色矩阵 46 imgAttributes.SetColorMatrix(colMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); 47 return imgAttributes; 48 } 49 public bool IsReusable 50 { 51 get 52 { 53 return false; 54 } 55 } 56 }
一般处理程序可以直接在浏览器中查看效果:
下面是水印图片效果:图片右下角“蓝色天空”是用PhotoShop做的文字图片