Archive

Archive for May, 2009

Loading Image from URL in Windows Forms

May 19th, 2009 Anuraj P 2 comments

Recently I got a chance to work on Windows Application, it is Twitter client using C#. In that I need to show some Image from a URL. I thought like Microsoft will provide some way to load Images from URL and I tried to do the same with “Image.FromFile” method. But it failed. :( Then I searched and found it will not supports Urls. So I developed an extention method for Image class, which will load from URL. I tried to Inherit from Image class, but that doesn’t work, it is not inheritable. :(

And here is the code

namespace dotnetthoughts
{
	public static class Utilities
	{
		public static Image FromURL(this Image image, string Url)
		{
			HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
			HttpWebResponse respone = request.GetResponse() as HttpWebResponse;
			return Image.FromStream(respone.GetResponseStream(),true);
		}
		public static Image FromURL(this Image image, string Url, string userName, string Password)
		{
			HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
			request.Credentials = new NetworkCredential(userName, Password);
			HttpWebResponse respone = request.GetResponse() as HttpWebResponse;
			return Image.FromStream(respone.GetResponseStream(), true);
		}
	}
}

In the second method, I am accepting the Username and Password, so it can access protected Images too.

Implementation of this code

//If we don't put null, C Sharp compiler will not allows to compile the application
Image img = null;
this.pictureBox1.Image = img.FromURL(this.textBox1.Text);
Categories: .Net, .Net 3.0 / 3.5, WPF Tags: , , ,