Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Download images from a URL in C#

You may use the following method to retrieve the image from a specific URL on the web. The below C# function takes an image url, download the image from the url as a stream and returns an image object. If the image could not be downloaded, it will return null.

  1. public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
  2. {
  3. System.Drawing.Image image = null;
  4.  
  5. try
  6. {
  7. System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
  8. webRequest.AllowWriteStreamBuffering = true;
  9. webRequest.Timeout = 30000;
  10.  
  11. System.Net.WebResponse webResponse = webRequest.GetResponse();
  12.  
  13. System.IO.Stream stream = webResponse.GetResponseStream();
  14.  
  15. image = System.Drawing.Image.FromStream(stream);
  16.  
  17. webResponse.Close();
  18. }
  19. catch (Exception ex)
  20. {
  21. return null;
  22. }
  23.  
  24. return image;
  25. }

The following code shows how to call the above function to download the image:
  1. protected void btnSave_Click(object sender, EventArgs e)
  2. {
  3. System.Drawing.Image image = DownloadImageFromUrl(txtUrl.Text.Trim());
  4.  
  5. string rootPath = @"C:\DownloadedImageFromUrl";
  6. string fileName = System.IO.Path.Combine(rootPath, "test.gif");
  7. image.Save(fileName);
  8. }