C# Code Snippet - Download Image from URL

C# Code Snippet - Download Image from URL

C# Code Snippet - Download Image from URL

(C-Sharp) C# code snippet download image from URL. This function download image using web response stream.

Bookmark:

C# Code Snippet - Download Image from URL

This .Net C# code snippet download image from URL. To use this function simply provide the URL of the image you like to download. This function read the image contents using URL and returns downloaded image as an image object. This function download image using web response stream.

/// <summary>
/// Function to download Image from website
/// </summary>
/// <param name="_URL">URL address to download image</param>
/// <returns>Image</returns>
public Image DownloadImage(string _URL)
{
    Image _tmpImage = null;

    try
    {
        // Open a connection
        System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

        _HttpWebRequest.AllowWriteStreamBuffering = true;

        // You can also specify additional header values like the user agent or the referer: (Optional)
        _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
        _HttpWebRequest.Referer = "http://www.google.com/";

        // set timeout for 20 seconds (Optional)
        _HttpWebRequest.Timeout = 20000;

        // Request response:
        System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

        // Open data stream:
        System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

        // convert webstream to image
        _tmpImage = Image.FromStream(_WebStream);

        // Cleanup
        _WebResponse.Close();
        _WebResponse.Close();
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        return null;
    }

    return _tmpImage;
}


Here is a simple example showing how to use above function (DownloadImage) to download image and show it in a PictureBox and how to save it on a local disk.

// Download web image
Image _Image = null;
_Image = DownloadImage("http://www.yourdomain.com/sample-image.jpg");

// check for valid image
if (_Image != null)
{
    // show image in picturebox
    pictureBox1.Image = _Image;

    // lets save image to disk
    _Image.Save(@"C:\SampleImage.jpg");
}


C# Keywords Used:

  • HttpWebRequest
  • WebResponse
  • Image
  • Stream
  • StreamReader
  • ExecuteReader
  • Exception

Code Snippet Information:

  • Applies To: .Net, C#, CLI, HTML, HttpWebRequest, WebResponse, StreamReader, Data Mining, Download Image from URL
  • Programming Language : C# (C-Sharp)

External Resources:

stephen :: February 02-2010 :: 12:40 PM

Put the requires namespaces in there, completely useless for console app!

aisteru :: April 27-2010 :: 06:56 AM

thanks man! this is really helpful!

Kenton :: June 24-2010 :: 10:14 PM

This is exactly what I was looking for, thanks!

Nicholas :: July 20-2010 :: 06:48 AM

An Exception(parameter is invalid ) is occured in this line '_tmpImage = Image.FromStream(_WebStream);'
Somebody can help me,Thanks

Angila :: August 19-2010 :: 09:24 AM

Very usefull. Thank you

Antone :: August 19-2010 :: 05:42 PM

Great snippet. Used this to get past the SharpPDF limitation of not being able to add an image reference to a web image.

Carlos Acevedo :: September 10-2010 :: 05:06 PM

Wonderful...
It is excactly I was searching for....

Thanks a lot...

Bassem :: September 29-2010 :: 08:08 PM

Very useful! Thanks

nam kazt :: November 14-2010 :: 06:39 PM

simple as like that

Using System.Net;
WebClient wb = new WebClient();
PictureBox1.Image = Image.FromStream(wb.OpenRead(s_img));

Hermes :: December 05-2010 :: 11:44 AM

the code is clear, simple and reusable in 5 seconds.
nice!!

Ranjith :: January 06-2011 :: 01:35 PM

Great post ... exactly what I was lookign for. Thanks alot and appreciate your work.

Anonymous :: January 31-2011 :: 05:52 PM

Good post. Very clear example. Should line 34/35 of the first code block read:

_WebResponse.Close();_HttpWebRequest.Close();

instead of

_WebResponse.Close();
_WebResponse.Close();

It looks as though you are closing the response twice while leaving the request open.

Ammo :: May 04-2011 :: 10:47 AM

Great - worked out of the box, unlike so many others which i tried.

thanks very much

Victor Pacheco :: April 19-2011 :: 08:50 PM

Good Job!!!

Sunil :: February 19-2011 :: 06:35 AM

Thanks.. the code is very simple and  works real fine..

Hakan Ugur :: August 01-2011 :: 01:19 PM

Thanks for sharing this great code. The only my concern is, we can use using keyword to create webresponse object which is disposable. If you have any exception and fall to catch block before kill the WebResponse objects, it will not be removed from memory properly.

kapil :: April 12-2011 :: 05:59 AM

i am benifited a more

Blackley1 :: March 14-2011 :: 05:30 AM

To those with little .net experience... The required namespace is:

System.Drawing;

after you add that it should work...

Param :: March 15-2011 :: 09:54 AM

Thanks, you saved me a lot of work

Sevan :: March 18-2011 :: 01:10 AM

Thanxxx :) it is so useful

rizwan :: March 31-2011 :: 12:02 AM

when i run this it give an error

"A generic error occurred in GDI+."

Kazie :: March 20-2011 :: 04:46 PM

Nam Kazt,

Certain websites do not like webclient.openread and refuse it on connection(Some not all).
This piece of code behaves as if the requesting function was a browser and therefore nothing can refuse it unless they want to refuse a browser viewing it.

Very useful code.

Behrad Moeinzadeh :: September 22-2011 :: 10:15 PM

Thanks a lot for providing this code, it worked exactly as it was promised.

Kishore :: October 03-2011 :: 11:18 AM

thanks! this is really helpful!

Leave a comment