Guy*_*Guy 13 c# png web-services image httphandler
我希望能够创建一个简单的PNG图像,比如使用基于ac#web的服务生成图像的红色方块,从<img src="myws.ashx?x=100>HTML元素调用.
一些示例HTML:
<hmtl><body>
<img src="http://mysite.com/webservice/rectangle.ashx?size=100">
</body></html>
Run Code Online (Sandbox Code Playgroud)
是否有人可以拼凑一个简单的(工作)C#课程来让我入门?一旦关闭和离开,我确信我可以完成这个以实际做我想要它做的事情.
TIA
解
rectangle.html
<html>
<head></head>
<body>
<img src="rectangle.ashx" height="100" width="200">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
rectangle.ashx
<%@ WebHandler Language="C#" Class="ImageHandler" %>
Run Code Online (Sandbox Code Playgroud)
rectangle.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;}
}
}
Run Code Online (Sandbox Code Playgroud)
Llo*_*oyd 21
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然这非常粗糙.那你就叫它:
<img src="myhandler.ashx?width=10&height=10"/>
Run Code Online (Sandbox Code Playgroud)