本文主要是介绍Asp.net网站开发(二)HttpHandler,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
模版和处理程序
封面数字水印:运用httphandler技术
封面数字水印的实现:
1.创建一个Ihttphandler的类Handler1
2.在Handler1中写代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
namespace WebApplication1
{/// <summary>/// Handler1 的摘要说明/// </summary>public class Handler1 : IHttpHandler{public void ProcessRequest(HttpContext context){//string path = "~/ProductImgs/";string a = context.Request.MapPath(path + context.Request.Params["id"].ToString() + ".jpg");Image m = null;if (File.Exists(a) ){m = Image.FromFile(a);Graphics g = Graphics.FromImage(m);g.DrawString("12345", new Font("宋体", 20), Brushes.Red, m.Width - 60, m.Height - 20);g.Dispose();}else{m = Image.FromFile(context .Request.MapPath (path ));}context.Response.ContentType = "image/jpeg";m.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);m.Dispose();context.Response.End();}public bool IsReusable{get{return false;}}}
}
3.修改Default.aspx中图片的src属性
<body><form id="form1" runat="server"><div><img alt="" class="style1" src="Handler1.ashx?id=1" /><img alt="" class="style2" src="Handler1.ashx?id=2" /><img alt="" class="style1" src="Handler1.ashx?id=3" /><img alt="" class="style2" src="Handler1.ashx?id=4" /></div></form>
</body>
运行结果如下:
数字水印的实现(全局方式)
1.修改web.config文件,在文件中添加以下代码行
<httpHandlers><addverb="* "path="ProductImgs/*.jpg" validate="false" type="WebApplication1.Handler1"/></httpHandlers>
Path:访问路径
Type:指定的处理程序
2.创建一个Ihttphandler的类Handler1
3. Handler1代码
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;using System.Drawing;namespace WebApplication1{///<summary>/// Handler1 的摘要说明///</summary>public class Handler1 : IHttpHandler{public void ProcessRequest(HttpContextcontext){//指定文件夹stringOL = "~/ProductImgs/default.jpg";//定义一个图片Imageimage = null;//判断地址是否存在if (File.Exists (context.Request.PhysicalPath )){//加载文件image = Image.FromFile(context.Request.PhysicalPath);//实例化画布Graphicsg = Graphics.FromImage(image );//在image上会在水印g.DrawString("hahahhahha", newFont("",20), Brushes.Red, image.Width-120,image.Height-25);//释放画布g.Dispose();}else{image = Image.FromFile(context .Request.MapPath(OL));}//设置输出类型为jpeg图片context.Response.ContentType = "image.jpeg";//将修改的图片存入文件流image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);image.Dispose();context.Response.End();}public bool IsReusable{get{returnfalse;}}}}
这篇关于Asp.net网站开发(二)HttpHandler的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!