【发布时间】:2010-10-27 15:25:31
【问题描述】:
我希望能够创建一个简单的 PNG 图像,例如使用基于 c# Web 的服务生成图像的红色方块,从<img src="myws.ashx?x=100> HTML 元素调用。
一些示例 HTML:
<hmtl><body>
<img src="http://mysite.com/webservice/rectangle.ashx?size=100">
</body></html>
有没有人可以拼凑一个简单的(工作的)C# 类来帮助我入门?一旦出发,我确信我可以完成这件事,真正做我想做的事。
- 最终目标是为显示性能指标等的数据驱动网页创建简单的红色/琥珀色/绿色 (RAG) 嵌入式状态标记*
- 我希望它使用 PNG,因为我预计将来会使用透明度*
- 请提供 ASP.NET 2.0 C# 解决方案...(我还没有生产 3.5 的机器)
tia
解决方案
矩形.html
<html>
<head></head>
<body>
<img src="rectangle.ashx" height="100" width="200">
</body>
</html>
矩形.ashx
<%@ WebHandler Language="C#" Class="ImageHandler" %>
矩形.cs
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int width = 600; //int.Parse(context.Request.QueryString["width"]);
int height = 400; //int.Parse(context.Request.QueryString["height"]);
Bitmap bitmap = new Bitmap(width,height);
Graphics g = Graphics.FromImage( (Image) bitmap );
g.FillRectangle( Brushes.Red, 0f, 0f, bitmap.Width, bitmap.Height ); // fill the entire bitmap with a red rectangle
MemoryStream mem = new MemoryStream();
bitmap.Save(mem,ImageFormat.Png);
byte[] buffer = mem.ToArray();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(buffer);
context.Response.Flush();
}
public bool IsReusable {
get {return false;}
}
}
【问题讨论】:
-
你能让一个http处理程序返回一个图像吗?让我们说一个位图图像或一个字节 [] 缓冲区到一个 c# 方法(代码隐藏文件)从它被调用的地方?如果我听起来很愚蠢,我很抱歉,但我是 http 处理程序的新手
-
@YP,看到接受的答案了吗??否则我不明白你的意思,坦率地说,我也不知道该怎么做。我的 c# 是 bleh!
-
@guy 感谢您发布解决方案 - 帮了我很多!
标签: c# web-services png httphandler image