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?
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; } }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With