Sometimes you need to display an image that is not saved in a file. These could be dynamically generated or loaded from a file but were modified. To display them in an Image control you need to create another page that saves the image in its output stream.
As an example to demonstrate how to do this, I created a project with two aspx pages. The first page, default.aspx, is the one the user views and it contains the Image control that will display the dynamically generated image. The second one contains the code to generate the image, named imagegen.aspx. Delete all the HTML code in imagegen.aspx and leave the Page directive only. So the contents of imagegen.aspx should look like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="imagegen.aspx.cs"
Inherits="StreamedImage.imagegen" %>
The code below is in imagegen.aspx’s Page Load event. It creates an image with a white background and writes the current date and time on it. The Bitmap object’s Save method allows you to save the image to a file or a stream. And saving the image to Response.OutputStream sends it to the outgoing HTTP body. To get the image displayed in default.aspx just set the ImageURL property of the Image control to “imagegen.aspx”. Now everytime default.aspx is loaded a new image is generated with the loading date and time displayed in it.
protected void Page_Load(object sender, EventArgs e)
{
Bitmap image = new Bitmap(200, 200);
Graphics graphics = Graphics.FromImage(image);
Font font = new Font("Arial", 12);
graphics.FillRectangle(Brushes.White, 0, 0, 200, 200);
graphics.DrawString(DateTime.Now.ToString(), font, Brushes.DarkBlue, 5, 5);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
graphics.Dispose();
image.Dispose();
Response.Flush();
}
Free ASP.NET 5 Hosting
Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.