c# - 使用 C# HttpHandler webservice 创建 PNG 图像

标签 c# web-services png httphandler image

我希望能够创建一个简单的 PNG 图像,例如使用基于 c# Web 的服务生成图像的红色方 block ,从 <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 盒子)

蒂亚

解决方案

矩形.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;}
    }
}

最佳答案

Web 服务,尤其是 SOAP 需要诸如 XML 信封之类的内容,其中包含调用的详细信息。您最好使用 HttpHandler

像这样:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        int width = int.Parse(context.Request.QueryString["width"]);
        int height = int.Parse(context.Request.QueryString["height"]);

        using (Bitmap bitmap = new Bitmap(width,height)) {

            ...

            using (MemoryStream mem = new MemoryStream()) {
                bitmap.Save(mem,ImageFormat.Png);
                mem.Seek(0,SeekOrigin.Begin);

                context.Response.ContentType = "image/png";

                mem.CopyTo(context.Response.OutputStream,4096);
                context.Response.Flush();
            }
        }
    }

}

这当然很粗糙。你会这样调用它:

<img src="myhandler.ashx?width=10&height=10"/>

关于c# - 使用 C# HttpHandler webservice 创建 PNG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/887985/

相关文章:

java - 如何在 xsd 文件中指定架构位置?

C++ gdi::Bitmap 到内存中的 PNG 图像

c# - C# IHttphandler 上 jQuery 自动完成的随机排序请求

c# - 将本地 mssql 数据库移动到 web 托管的 MYSQL

c# - web 方法不更新 sql server 上的详细信息

web-services - 使用 Qooxdoo 从 Web 服务获取数据时遇到问题

swift - PNG 图像未保存到文档目录

Java缓冲图像: Alpha change makes low alpha areas appear black

c# - 使用 linq 调用方法 x 次

c# - 有没有办法让两个触发游戏对象发生碰撞?