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);
This entry was posted in .Net, .Net 3.0 / 3.5, WPF and tagged , , , . Bookmark the permalink.

0 Responses to Loading Image from URL in Windows Forms

  1. zproxy says:

    Did you know you could use this syntax instead:

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

  2. anuraj says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>