19 April, 2010

Streaming images to/from website

If you want to “disguise” the origin of your image files or just want more control of the way images are sent to the Client; you can resolve to streaming the images instead of providing them via conventional disk load. By interacting with this process, you are able to control in a more granular way how the images are resized, tagged or any other operation you want to perform before delivering the images to the client. Maybe you simply want to add a watermark before sending them to the client browser? The below 2 images are both coming from a generic httphandler serving these images to the .aspx page.


How is this accomplished?

The way this is accomplished is this. I have a simple web application (Imageserver.POC) here.

image As seen in the figure, the project consists of 3 important files:
1) DisplayPage.aspx (conventional aspx-page)
2) ImageProvider.ashx (generic http-handler)
3) ResponseStreamer.cs (handles pushing image to client)

The displayPage.aspx is a conventional .aspx page with embedded image controls (see below). Note the way the ImageUrl is formatted (pointing to the ImageProvider.ashx):


By referencing the ImageProvider in this way – the ImageControls (Image1 and Image2) are not bound directly to a physical file, but instead to a httphandler serving the request.

ImageProvider.ashx (httphandler)

The ImageProvider.ashx is very simple in this example. It implements the IHttpHandler interface and has one method (ProcessRequest). In the example it only checks if a querystring exists (a more advanced scenario would most likely be added here). If the querystring count > 0, it serves the photo called “photo.jpg” to the client. And in the above example, the Client is an “<asp:image” control ;-).


The ImageProvider uses a helper class (ResponseStreamer) to actually push the image to the client via the Response object. This class is seen below:



You can most likely come up with additional processing and checks to make before serving the image to the Client, but all control is in the hands of the server developer by using the above method.

No comments: