栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

理解HttpHandler,并为所有*.jpg图片生成一段文字于图片上

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

理解HttpHandler,并为所有*.jpg图片生成一段文字于图片上

接口IHttpHandler的定义如下:
复制代码 代码如下:
interface IHttpHandler
{
void ProcessRequest(HttpContext ctx);
bool IsReuseable { get; }

1新建一网站,名为MyHttpHandlerTest
2右击添加,选择类库,取名为MyHttpHandler
3-在上一步新建的类库上右键添加System.Web引用

主要代码:
复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
namespace MyHttpHandler
{
public class Class1:IHttpHandler,IRequiresSessionState
{
#region IHttpHandler成员
public bool IsReusable
{
get { return true; }
}

public void ProcessRequest(HttpContext context)
{
context.Response.Write("handler处理");
}
#endregion
}
}

4-在MyHttpHandler类库上右键,生成,取名为MyHttpHandler

5-在web.config中的system.web节点中天下如下节点




6-在MyHttpHandlerTest右键添加引用,选择项目找到刚才编译后的.dll文件

7-运行Handler1.aspx,页面显示:

下面我们利用HttpHandler将一段文字生成于图片中
添加一个类,默认为Class.cs
复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
///
/// Class1 的摘要说明
///

public class Class1:IHttpHandler
{
public Class1()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public bool IsReusable
{
get { return true; }
}
private static Image OldImage = null;
private static Image GetOldImage(HttpContext context)
{
if (OldImage == null)
{
OldImage = Image.FromFile(context.Server.MapPath("~/Images/Old.jpg"));
}
return OldImage.Clone() as Image;
}
public void ProcessRequest(HttpContext context)
{
Image newimage = GetOldImage(context);
Graphics gh = Graphics.FromImage(newimage);
Font font = new Font("Monaco", 24.0f, FontStyle.Regular);
string writetext = HttpUtility.UrlEncode(context.Request.QueryString["writetext"]);
gh.DrawString(HttpUtility.UrlDecode(writetext), font, new SolidBrush(Color.LightBlue), 20.0f, newimage.Height - font.Height - 30);
newimage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
gh.Dispose();
newimage.Dispose();
}
}

新建一个.aspx页面,添加一个Hyperlink控件,再在其.cs文件中添加一段代码传值
复制代码 代码如下:
protected void Page_Load(object sender, EventArgs e)
{
Hyperlink1.NavigateUrl = "img.jpg?writetext=" + HttpUtility.UrlEncode("大蜗牛");
}

另外还需在web.config文件中将httpHandlers节点中改为如下

表明对所有的.jpg格式的文件才会处理
参考《道不远人 深入解析asp.net 2.0控件开发》
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/58408.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号