C # Image Generator - Slow Performance

I recently worked on an aspx dynamic image generator in C #, which in its most basic state takes the querystring value from "t" and writes this string to the image, and then returns a jpg.

It worked flawlessly locally, and on a test server — images returned instantly.

But when on load-balanced live servers it sometimes works fine. But more often than often, time is running out / takes a minute to return the image.

I thought I was asking here if there is something obvious in my code that will cause problems before I go to the server operators to ask why this is not working well.

Below is a very optimized version of the generator (which also has the same timeout problems)

protected void Page_Load(object sender, EventArgs e)
{

    // Set global stage dimensions
    const int stageWidth = 500;
    const int stageHeight = 200;

    // Create Bitmap placeholder for new image       
    Bitmap createdImage = new Bitmap(stageWidth, stageHeight);

    // Draw new blank image
    Graphics imageCanvas = Graphics.FromImage(createdImage);

    // Add text
    if (!string.IsNullOrEmpty(Request.QueryString["t"]))
    {
        string imageText = Uri.UnescapeDataString(Request.QueryString["t"]).Trim();
        Font font = new Font("Arial", 22);
        imageCanvas.DrawString(imageText, font, Brushes.White, 0, 0);            
    }

    // Save
    MemoryStream memStream = new MemoryStream();
    createdImage.Save(memStream, ImageFormat.Jpeg);
    imageCanvas.Dispose();
    createdImage.Dispose();

    // Set filename / image format
    Response.AppendHeader("content-disposition", "filename=MyImage");
    Response.ContentType = "image/jpeg";        

    // Send output to client
    memStream.WriteTo(Response.OutputStream);
    memStream.Dispose();
    Response.Flush();
}
+5
2

, :

  • using.
  • ashx. , aspx. http, . , .
  • . , asp.net, , t, - .
  • , : , . , ,

-. , , .

, .

+3

, , , :

createdImage.Save(Response.OutputStream, ImageFormat.Jpeg); 

, .aspx. . http-:

public class MyHttpHandler : IHttpHandler
{
   public void ProcessRequest(HttpContext context)
   {
      // prepare image like you did
      memStream.WriteTo(context.Response.OutputStream);
   }

   // Override the IsReusable property.
   public bool IsReusable
   {
      get { return true; }
   }
}
+1

All Articles