Thursday, May 24, 2007

Changing the Content Type of a Web Page

Some times we want to get an image dynamically from a ASP .NET web form.
So we just create a web form containing an ImageControl. Then in this form we set a value on Session.

protected void Page_Load(object sender,EventArgs e)
{

// Putting some files path on session
Session["MyValue"] = "myImage.gif";
}


Now I want another web page which is create/load an image depending on the value I 've put in Session. And then I set the ImageUrl of that Image control to my new web page. Like this:


<asp:Image ID="imgDynamic" runat="server" ImageUrl="~/getimages.aspx" />

Notice that ImageUrl have been set to an aspx file!

Now in my GetImages web form I have to decide to create/load the image depending on the value of Session variable. The important point is that the output of this web form is not HTML code, instead I is responding some images. So I have to change the content type of my web page. And finally I have to put my Image to the Response of my web page. For these I just write these lines of code:

protected void Page_Load(object sender, System.EventArgs e)
{
// Create/Load the image from the string value in session
Bitmap b = new Bitmap(Server.MapPath(Request.ApplicationPath) + "\\Images\\" + Session["MyValue"].ToString());

// Change the response headers to output a JPEG image.
this.Response.Clear();
this.Response.ContentType = "image/jpeg";

// Write the image to the response stream in JPEG format.
b.Save(this.Response.OutputStream, ImageFormat.Jpeg);

}

Download the sample code:
http://www.tabatabaei.info/csharpsamples/dynamicImage.zip

1 comment:

Nader Khaled said...

Thank you it's useful

ContentType = "image/jpeg"
if file is XML,pdf,avi,mp3....
ContentType = "???"