How to use Visual Studio 2012 to Download Images from Websites

Introduction

As you might know, I have always been fascinated with Wallpapers and photos. What you might not know is that I appreciate good art as well, seeing the fact that my wife is quite good at painting and creating things out of nothing.

I have a huge collection of wallpapers. Some of you might remember this old dinosaur project of mine, which I still use successfully to change my desktop backgrounds. Because of the tedious nature of collecting new wallpapers, I have decided to make a little tool to do all the hard work for me. With this article I will demonstrate how to download images from a webpage. Note: some pictures are copyrighted, and must not be used in any way. I am not advocating that. I am using pictures from websites that provide them for free.

Anyways, enough about me, let us get started with our little project

Design

Fire up Visual Studio 2012 and choose your desired programming language. I will illustrate both VB.NET as well as C#.

Design your form to resemble Figure 1.

Our Design
Figure 1 - Our Design

Code

Not much coding needed from our side. Let's start with importing the Namespaces.

VB.NET

Imports System.IO 'File Functions

C#

using System.IO; //For File Functions

Now let's handle the navigation button that will enable us to navigate to a site:

VB.NET

    Private Sub btnIDGo_Click(sender As Object, e As EventArgs) Handles btnIDGo.Click

        wbID.Navigate(txtIDURL.Text) 'Navigate To URL

    End Sub

C#

        private void btnIDGo_Click(object sender, EventArgs e)
        {
            
            wbID.Navigate(txtIDURL.Text); //Navigate To URL

        }

The above code segment instructs the WebBrowser Control to navigate to the entered site. This also assumes your WebBrowser Control was named wbID as was the case with mine.

Now the fun starts!

Add the next code segment:

VB.NET

    Private Sub btnIDGet_Click(sender As Object, e As EventArgs) Handles btnIDGet.Click

        Dim wcObj As New System.Net.WebClient() 'Create New Web Client Object

        Dim hecImages As HtmlElementCollection = wbID.Document.GetElementsByTagName("img") 'Browse Through HTML Tags

        Dim strWebTitle As String 'Web Page Title
        Dim strPath1 As String 'Folder Path
        Dim strPath2 As String 'Sub Folder Path

        strWebTitle = Me.wbID.DocumentTitle  'Obtain Web Page Title

        strPath1 = "c:\" & strWebTitle 'Create Folder Named Web Page Title
        strPath2 = strPath1 & "\Images" 'Create Images Sub Folder

        Dim diTitle As DirectoryInfo = Directory.CreateDirectory(strPath1)
        Dim diImages As DirectoryInfo = Directory.CreateDirectory(strPath2)

        For i As Integer = 0 To hecImages.Count - 1 'Loop Through All IMG Elements Found

            'Download Image(s) To Specified Path

            wcObj.DownloadFile(hecImages(i).GetAttribute("src"), strPath1 & "\images\" & i.ToString() & ".jpg")
        Next

    End Sub

C#

        private void btnIDGet_Click(object sender, EventArgs e)
        {

            System.Net.WebClient wcObj = new System.Net.WebClient(); //Create New Web Client Object

            HtmlElementCollection hecImages = wbID.Document.GetElementsByTagName("img"); //Browse Through HTML Tags

            string strWebTitle; //Web Page Title
            string strPath1; //Folder Path
            string strPath2; //Sub Folder Path

            strWebTitle = this.wbID.DocumentTitle; //Obtain Web Page Title

            strPath1 = @"c:\" + strWebTitle; //Create Folder Named Web Page Title
            strPath2 = strPath1 + "\\Images"; //Create Images Sub Folder

            DirectoryInfo diTitle = Directory.CreateDirectory(strPath1);
            DirectoryInfo diImages = Directory.CreateDirectory(strPath2);

            for (int i = 0; i < hecImages.Count; i++) //Loop Through All IMG Elements Found
            {

                //Download Image(s) To Specified Path
                wcObj.DownloadFile(hecImages[i].GetAttribute("src"), strPath1 + "\\images\\" + i.ToString() + ".jpg");
            
            }

        }

We create a webclient object to assist us later in downloading the images. We then create an HTMLElementCollection object, which helps us identify all Image tags on the webpage. If you do not have a basic understanding of HTML, I suggest you have a look here.

We store the Webpage's title and create a folder on C:\ with the same name. Inside this folder we create a subfolder named Images. This is where we will download our pictures to.

The fun part here is the loop. We use a for loop to loop through all of the images found and save them via the DownloadFile method of the WebClient object. We find the image's location through the HTML IMG Tag's SRC attribute. Voila! Quick and simple.

Conclusion

Although this is but a small tool, its possibilities are endless. I am including the Source files just in case you missed something. Until next time, cheers from a lazy Hannes!



Related Articles

Downloads

Comments

  • Not working with me

    Posted by Muhamad on 04/23/2014 01:24am

    wbID is not defined , when I try to define it by : Dim wbID As New WebBrowser it points null reference to the line : Dim hecImages As HtmlElementCollection = wbID.Document.GetElementsByTagName("img") I am using VB.NET 2005 thanks.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds