本例通过httphandle在页面上画矩形色条来演示HttpHandle用法
web.config关键配置,加在system.web中任何地方都行
显示页面default.aspx代码
类库代码:
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace ClassLibrary1
{
public class Class1:IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string c = context.Request["c"];
string cr = context.Request["r"];
string cg = context.Request["g"];
string cb = context.Request["b"];
if (!string.IsNullOrEmpty(c))
{
int ir = 200;
int ig = 200;
int ib = 200;
int count = 0;
int.TryParse(cr, out ir);
int.TryParse(cg, out ig);
int.TryParse(cb, out ib);
int.TryParse(c,out count);
Color cc = Color.FromArgb(ir, ig, ib);
Bitmap b = new Bitmap(count, 20);
Graphics g = Graphics.FromImage(b);
MemoryStream m = new MemoryStream();
SolidBrush sb = new SolidBrush(cc);
try
{
g.FillRectangle(sb, 0, 0, count, 20);
b.Save(m, ImageFormat.Png);
context.Response.ContentType = "image/png";
context.Response.OutputStream.Write(m.ToArray(), 0, (int)m.Length);
}
catch
{
m.Close();
sb.Dispose();
sb = null;
g.Dispose();
g = null;
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
web.config关键配置,加在system.web中任何地方都行
<httpHandlers>
<add verb="*" path="img.xy" type="ClassLibrary1.Class1,ClassLibrary1"/>
</httpHandlers>
显示页面default.aspx代码
<table width="70%" border="1">
<tr>
<td>标题</td>
<td>标识</td>
</tr>
<tr>
<td>实现动态生成图片</td>
<td><img src="img.xy?c=100" /></td>
</tr>
<tr>
<td>实现动态</td>
<td><img src="img.xy?c=50&r=<%=Request["r"] %>&g=<%=Request["g"] %>&b=<%=Request["b"] %>" /></td>
</tr>
</table>
上面一个带了参数,一个没带参数
运行结果: