e = Image.FromFile(context.Request.MapPath(defaultimage));//如果不存在图片就输出defaultimage。 44 } 45 context.Response.ContentType = "image/jpeg";//输出图片的类型 46 image.Save(context.Response.OutputStream, ImageFormat.Jpeg);//将图片存入输出流 47 image.Dispose(); 48 context.Response.End(); 49 } 50 51 public bool IsReusable 52 { 53 get 54 { 55 return false; 56 } 57 } 58 }
这样当Image控件访问Handler的时候就可以输出图片了。
二、全局Handler:
在aspx里面输入 <asp:Image ID="Image1" runat="server" ImageUrl="image/9221944.jpg" />就可以了。不需要请求Handler。然后在项目中单击右键添加新项,选择类。然后输入如下代码:
MyBookMark 的代码
1 using System; 2 using System.Data; 3 using System.Configuration; 4 using System.Web; 5 using System.Web.Security; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 using System.Web.UI.WebControls.WebParts; 9 using System.Web.UI.HtmlControls; 10 using System.IO; 11 using System.Drawing.Imaging; 12 using System.Drawing; 13 14 /// <summary> 15 /// MyBookMark 的摘要说明 16 /// </summary> 17 public class MyBookMark : IHttpHandler 18 { 19 public MyBookMark() 20 { 21 // 22 // TODO: 在此处添加构造函数逻辑 23 // 24 } 25 26 #region IHttpHandler 成员 27 28 public bool IsReusable 29 { 30 get { return false; } 31 } 32 33 private const string waterimage = "~/image/Watermark.jpg"; //水印图片 34 private const string defaultimage = "~/image/default.jpg"; //没有找到图片时显示的图片 35 private const float alpha = 0.5F; //透明度 36 37 public void ProcessRequest(HttpContext context) 38 { 39 40 System.Drawing.Image image; 41 42 if (System.IO.File.Exists(context.Request.PhysicalPath)) 43 { 44 image = System.Drawing.Image.FromFile(context.Request.PhysicalPath); 45 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); 46 System.Drawing.Image watermark = System.Drawing.Image.FromFile(context.Request.MapPath(waterimage)); 47 float[][] nArray ={ new float[] {1, 0, 0, 0, 0}, 48 new float[] {0, 1, 0, 0, 0}, 49 new float[] {0, 0, 1, 0, 0}, 50 new float[] {0, 0, 0,alpha , 0}, 51 new float[] {0, 0, 0, 0, 1}}; 52 ColorMatrix colormatrix = new ColorMatrix(nArray); 53 ImageAttributes attributes = new ImageAttributes(); 54 attributes.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); 55 g.DrawImage(watermark, new Rectangle(image.Width - watermark.Width, image.Height - watermark.Height, 56 watermark.Width, watermark.Height), 0,0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, attributes);//在图片指定坐标处放入一个矩形图片内容为水印图片 57 g.Dispose(); 58 watermark.Dispose(); 59 } 60 else 61 { 62 ima |