The following example shows how to write a MemoryStream to the OutputStream of the Response object in ASP.NET. To use this code, create a new Web Application. Next, create a new web page in that application and name it getimage.aspx. Place the following code in the code behind for that page. In your Default.aspx page, drag and drop an image control and set the ImageUrl property equal to getimage.aspx?image=somefilename.jpg. Replace "somefilename.jpg" with an image file located in your web application's main directory.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;
public partial class getimage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string imageFile = Request.QueryString["img"].ToString();
if (imageFile == null || imageFile == "")
return;
Response.ContentType = "image/" + System.IO.Path.GetExtension(imageFile);
System.Drawing.Bitmap image = System.Drawing.Bitmap.FromFile(AppDomain.CurrentDomain.BaseDirectory + imageFile) as System.Drawing.Bitmap;
if (image == null)
{
Response.Write("null");
return;
}
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
memoryStream.WriteTo(Response.OutputStream);
memoryStream.Close();
memoryStream.Dispose();
image.Dispose();
}
}