This idea came about when I was writing an application for a client, in which the client insisted that the images not be stored in the database, but in a web repository. Although I initially resisted the idea, but the more I thought about it, the more it grew on it. For one thing, it offered an alternative to image storage to the database (which is the standard), or to the local drive (which I despise). The other advantage is that it would work really well with a web application that uses the same image.
I whipped up this simple application as a proof of the concept above. What this application does is that it streams the image given the URL, and displays it in a
PictureBox control. To use the application, just unzip it and double-click the executable.
- The first image it attempts to stream will be a bit slow. Consequent image streams will be faster.
- The application assumes that you're not behind a proxy. If you are, you will have to make some minor changes to the source code, and recompile.
To stream images from the web, we're going to make use of classes from the
System.IO classes. And of course, you're gonna need an Internet access as well.
private Image GetImage(string sURL)
Stream str = null;
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
str = wRes.GetResponseStream();
The first thing that I did is to create an
HttpWebRequest object from the Image URL, which is basically a class that manages the request to the URL given. If you're behind a proxy, then you will have to create a
WebProxy object and assign it to
GetResponse will get the resulting response from the request we made. What we're really interested is the data stream of the URL, which we obtain from the
GetResponseStream method of the
HttpWebResponse class. Once we have the stream, it's a simple matter to create an
Image object from the data stream.
- Create a screen to specify if the web request should go through a proxy.
- Allow the user to key in the URL, as opposed to hard-coding it.
Streaming images from the web onto a Windows application may not always be the ideal way to do things, but for some situations, it might actually save you some time and work. It did for me, so I hope some of you reading this might find some use out of it.
Comments and criticism are most welcome.