C++/CLI Code Snippet - Download Image from URL

C++/CLI Code Snippet - Download Image from URL

C++/CLI Code Snippet - Download Image from URL

C++/CLI code snippet download image from URL. This function download image using web response stream.

Bookmark:

C++/CLI Code Snippet - Download Image from URL

This .Net C++/CLI 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>
System::Drawing::Image ^DownloadImage(System::String ^_URL)
{
    System::Drawing::Image ^_tmpImage = nullptr;

    try
    {
        // Open a connection
        System::Net::HttpWebRequest ^_HttpWebRequest = safe_cast<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 nullptr;
    }

    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
System::Drawing::Image ^_Image = nullptr;
_Image = DownloadImage("http://www.yourdomain.com/SampleImage.gif");

// check for valid image
if (_Image != nullptr)
{
    // show image in picturebox
    pictureBox1->Image = _Image;

    // lets save image to disk
    _Image->Save("C:\\SampleImage.gif");
}


C++/CLI 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++/CLI

External Resources:

Leave a comment