title: Create PNG image with C# HttpHandler webservice
body: <p>I'd like to be able to create a simple PNG image, say of a red square using a c# web based service to generate the image, called from an <code>&lt;img src="myws.ashx?x=100&gt;</code> HTML element.</p>
  
  <p>some example HTML:</p>
  
  <pre><code>&lt;hmtl&gt;&lt;body&gt;
       &lt;img src="http://mysite.com/webservice/rectangle.ashx?size=100"&gt;
  &lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>Is there is anyone who can cobble together a simple (working) C# class just to get me started?  Once off and going I'm sure I can finish this off to actually do what I want it to do.</p>
  
  <ul>
  <li>End game is to create simple Red/Amber/Green (RAG) embedded status markers for a data driven web page that shows performance metrics etc*</li>
  <li>I'd like it to use PNG's as I anticipate using transparency in the future*</li>
  <li>ASP.NET 2.0 C# solution please... (I don't have a production 3.5 box yet)</li>
  </ul>
  
  <p>tia</p>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>rectangle.html</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;&lt;/head&gt;
  &lt;body&gt;
      &lt;img src="rectangle.ashx" height="100" width="200"&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>rectangle.ashx</p>
  
  <pre><code>&lt;%@ WebHandler Language="C#" Class="ImageHandler" %&gt;
  </code></pre>
  
  <p>rectangle.cs</p>
  
  <pre><code>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;}
      }
  }
  </code></pre>