Home > .Net, .Net 3.0 / 3.5, WPF > Loading Image from URL in Windows Forms

Loading Image from URL in Windows Forms

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: , , ,
  1. May 19th, 2009 at 07:52 | #1

    Did you know you could use this syntax instead:

    # this.pictureBox1.Image = default(Image).FromURL(this.textBox1.Text);

  2. May 26th, 2009 at 09:47 | #2

    Thanks Zproxy [:)], thanks for the information.

  1. No trackbacks yet.