有时项目里我们必须将图片进行一定的操作,例如水印,下载等,为了方便和管理我们可以自定义一个HttpHander 来负责这些工作
后台:
public class ImageHandler : IHttpHandler { #region IHttpHandler Members public bool IsReusable { get { return true; } } /// <summary> /// 实现IHTTPHandler后必须实现的方法 /// </summary> /// <param name="context">HttpContext上下文</param> public void ProcessRequest(HttpContext context) { context.Response.Clear(); //得到图片名 var imageName = context.Request["ImageName"] == null ? "逆时针的风" : context.Request["ImageName"].ToString(); //得到图片ID,这里只是演示,实际项目中不是这么做的 var id = context.Request["Id"] == null ? "01" : context.Request["Id"].ToString(); //得到图片地址 var stringFilePath = context.Server.MapPath(string.Format("~/Image/{0}{1}.jpg", imageName, id)); //声明一个FileStream用来将图片暂时放入流中 FileStream stream = new FileStream(stringFilePath, FileMode.Open); using (stream) { //透过GetImageFromStream方法将图片放入byte数组中 byte[] imageBytes = this.GetImageFromStream(stream,context); //上下文确定写到客户短时的文件类型 context.Response.ContentType = "image/jpeg"; //上下文将imageBytes中的数据写到前段 context.Response.BinaryWrite(imageBytes); stream.Close(); } } /// <summary> /// 将流中的图片信息放入byte数组后返回该数组 /// </summary> /// <param name="stream">文件流</param> /// <param name="context">上下文</param> /// <returns></returns> private byte[] GetImageFromStream(FileStream stream, HttpContext context) { //通过stream得到Image Image image = Image.FromStream(stream); //加上水印 image = SetWaterImage(image, context); //得到一个ms对象 MemoryStream ms = new MemoryStream(); using (ms) { //将图片保存至内存流 image.Save(ms, ImageFormat.Jpeg); byte[] imageBytes = new byte[ms.Length]; ms.Position = 0; //通过内存流读取到imageBytes ms.Read(imageBytes, 0, imageBytes.Length); ms.Close(); //返回imageBytes return imageBytes; } } /// <summary> /// 为图片加上水印,这个方法不用在意,只是演示,所以没加透明度 /// 下次再加上吧 /// </summary> /// <param name="image">需要加水印的图片</param> /// <param name="context">上下文</param> /// <returns></returns> private Image SetWaterImage(Image image,HttpContext context) { Graphics graphics = Graphics.FromImage(image); Image waterImage = Image.FromFile(context.Server.MapPath("~/Image/逆时针的风01.jpg")); //在大图右下角画上水印图就行 graphics.DrawImage(waterImage, new Point { X = image.Size.Width - waterImage.Size.Width, Y = image.Size.Height - waterImage.Size.Height }); return image; } #endregion }
别忘了还要在Web.Config中进行配置,别忘记verb和path属性,否则会报错
<httpHandlers> <add type="ImageHandler.ImageHandler,ImageHandler" verb="*" path="ImageHandler.apsx"/> </httpHandlers>
这样前台便能使用了
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> About </h2> <p> Put content here. <asp:Image runat="server" ImageUrl="ImageHandler.apsx?ImageName=逆时针的风&Id=02" /> </p> </asp:Content>
输出结果
时间: 2024-10-07 15:13:50