Thursday, October 23, 2008

Dynamically Render an Image on a Web Page ASP.net

I have used this trick so many times, I am somehow surprised that Microsoft don't have the built in functionality for rendering an image at runtime on a web page. All that needs to be done is creating a new .aspx page (we will call it RenderImage.aspx) within your project and in the Page_Load method, insert the following code.

byte[] ImageInfo = //get 
  MemoryStream s = new MemoryStream();
            try
            {
              s  = new MemoryStream(ImageInfo );
            }
            catch (Exception ex)
            {

            }
if (s.Length != 0)
            {
                        Response.BinaryWrite(ImageInfo) ;
}

Call it from another .aspx like so :

Image2.ImageUrl = "RenderImage.aspx";

Couldn't be easier.....well you say that now....just keep in mind that if you are using an UpdatePanel with ajax, that the call to BinaryWrite will not be liked, as it causes a MemoryStream error. 

      

No comments: