Download images from a URL using C#
Many times you may wanted to share an image from an external website, but found it hard to download it first to your local computer and then upload to your blog or website? This C# code sample shows how to programmatically download an image from a website and save to your website on your web server.
This code sample shows how to download an image from a website URL and save to your web server. This example uses the .NET class System.Net.HttpWebRequest to download the image stream to save to the computer. I am using C# syntax for the purpose of this sample, but you can easily convert it into any other .NET languages including VB.NET.Function to Download Image from URL
You may use the following method to retrieve the image from a specific URL on the web:
public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
{
System.Drawing.Image image = null;
try
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 30000;
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
image = System.Drawing.Image.FromStream(stream);
webResponse.Close();
}
catch (Exception ex)
{
return null;
}
return image;
}
The above 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.How to call the method to download image?
The following code shows how to call the above function to download the image:
protected void btnSave_Click(object sender, EventArgs e)
{
System.Drawing.Image image = DownloadImageFromUrl(txtUrl.Text.Trim());
string rootPath = @"C:\DownloadedImageFromUrl";
string fileName = System.IO.Path.Combine(rootPath, "test.gif");
image.Save(fileName);
}
NOTE: In the above sample, I have used a hard coded folder name and hard coded image name. You will have to be smart to detect the type of the image and save to a unique name in the folder to avoid conflicts. Read the code sample Find file extension from System.Drawing.Image object to find how to get the file extension from the image object.
