Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Bitmap to HTML

Tags:

html

c#

asp.net

I have an ASP.NET web form. This web form has an event handler that generates some HTML. This HTML is based on the time-of-day, that is why it is created in the event handler. Based on the time of day, an image is created programmatically via the following method:

private Bitmap GetImageForTime(DateTime time)
{
  Bitmap bitmap = new Bitmap();

  // Dynamically build the bitmap...

  return bitmap;
}

I want to call this method when the HTML is being generated. However, I do NOT want to write the image on the server. Instead, I would like to figure out a way to write it out along with the HTML. In a sense, I'm trying to accomplish the following:

protected void myLiteral_Load(object sender, EventArgs e)
{
  string html = "<table><tr><td>";
  html += GetImageForTime(DateTime.Now);  // This is the problem because it's binary.
  html += "</td><td>";
  html += GetWeatherHtmlText();
  html += "</td></tr></table>";
  myLiteral.Text = html;
}

Is this possible? If so, how?

like image 288
user208662 Avatar asked Dec 29 '22 12:12

user208662


2 Answers

I would suggest implementing an IHttpHandler that generates your image and returns it as a byte stream. Then in the tag on the page, set the src attribute to the address of the HTTP Handler.

<html><body><img src="TimeImageHandler.ashx"/></body></html>

Example: http://www.c-sharpcorner.com/uploadfile/desaijm/httphandlersforimages11152005062705am/httphandlersforimages.aspx

Generic HTTP Handlers are pretty simple to create once you're aware of them:

public class TimeImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Bitmap bitmap = GetImageForTime(DateTime.Now);
        context.Response.ContentType = "image/jpeg";
        bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }

    public bool IsReusable { get { return false; } }
}
like image 80
Toby Avatar answered Dec 31 '22 13:12

Toby


The way I have done this is to create an image tag in the HTML and point the image source (<img src="xxx" />) to a page that dynamically creates the image and returns that (and only that) on the response stream, with the correct mime type.

like image 24
Oded Avatar answered Dec 31 '22 14:12

Oded