Working with Streams

In addition to working with files, you can perform any operation using streams. Streams allow you to process images using other libraries, store data in the memory or databases, download images from a URL, and send them through HttpResponse.

.NET Framework provides a number of classes derived from the abstract System.IO.Stream class. To load an image from a stream you can use an appropriate format reader or the Bitmap.#ctor constructor. Similarly, to save an image to a stream, use an appropriate format writer or the Bitmap.Save(Stream, WriterSettings) method.

This topic describes how to send an image from a server to a client browser. The Working with Databases and Working with URLs topics explain using streams with databases and URLs.

To send any data from a server to a client, ASP.NET provides a special intrinsic Response object. Its OutputStream property allows the sending of data to a client when you write anything into this stream. Use this property as an input parameter for a format writer or the Bitmap.Save(Stream, WriterSettings) method.

The following code reads JPEG image, resizes it, and writes the result to the response output stream. The code uses pipelines; if you are not familiar with pipelines, read the Understanding Image Processing Approaches in Graphics Mill topic.

public void ProcessRequest(HttpContext context)
    int size = Convert.ToInt32(context.Request.QueryString["size"]);

    using (var reader = ImageReader.Create(context.Server.MapPath(@"Images\in.jpg")))
    using (var resize = new Resize(size, 0, ResizeInterpolationMode.High))
    using (var writer = new JpegWriter(context.Response.OutputStream))
        context.Response.ContentType = "image/png";
        Pipeline.Run(reader + resize + writer);

Usually, an image should be displayed along with some additional HTML. And if you write binary data into the response output stream, a client browser cannot handle HTML code sent into the same stream. So, you need a workaround to avoid this and display the resulting image and additional HTML on one page. To perform this action, create a separate page containing all necessary HTML code. At the position you want to display the image, add the <img> tag and set its src attribute to the page containing the previous code snippet (let us name it Streams.ashx).

The following code inserts the resulting image to an HTML page:

    <img src="Streams.ashx?size=150" /> 

See Also