Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Bing Image Download

, 30 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Microsoft's Bing has some amazing images as backgrounds. With this code you can create a Windows Service or any other type of application to automate the image download process, then set the Windows Desktop backgrounds to use the designated folder.

Introduction

Microsoft’s Bing has some amazing images as backgrounds; however, if you want to use them as background images for your Windows Desktop, you must go through the tedious process of opening your browser and saving the image as a background each day.

Unless you can automate the process that is.

Finding the images

The first step in the process is to find the images. Since they are the background on the webpage, the image must be downloaded to your Temporary Internet Files folder; however, these files have sometimes cryptic names, can be removed when cleaning the temporary files, and of course, you must visit Bing to initiate the download.

Long Zheng at www.istartedsomething.com has created an excellent archive of all Bing images, yet the problem is, through there is an RSS feed available, they are not downloadable directly from this site. There are instructions available here: http://www.makeuseof.com/tag/how-to-set-a-bing-wallpaper-desktop-slideshow-in-windows-7/ on creating a Theme file using the RSS feed; however, I’ve found this method to be unreliable.

Through some investigation, I found the image information is available from Bing using this URL: http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US.

As the format parameter indicates, this will return an XML formatted stream that contains information such as the date the images is for, the relative URL, description, and copyright information.

The idx parameter tells where you want to start from. 0 would start at the current day, 1 the previous day, 2 the day after that, etc. For instance, if the date were 1/30/2011, using idx = 0, the file would start with 20110130; using idx = 1, it would start with 20110129; and so forth.

The n parameter tells how many images to return. n = 1 would return only one, n = 2 would return two, and so on.

The mkt parameter tells which of the eight markets Bing is available for you would like images from. The valid values are: en-US, zh-CN, ja-JP, en-AU, en-UK, de-DE, en-NZ, en-CA.

Automating the download

Now that you know where to get the images from, it is easy to create an automated process to download them.

public class BingImages
{
    private const string DOWNLOAD_PATH = @"D:\BingImages";
    private const string BING = "http://www.bing.com";
    private const string IMG_URL = "http://www.bing.com/HPImageArchive" + 
                                   ".aspx?format=xml&idx=0&n={0}&mkt={1}";
    private static string[] Markets = new string[] { "en-US", "zh-CN", 
                                      "ja-JP", "en-AU", "en-UK", 
                                      "de-DE", "en-NZ", "en-CA" };
    private const int NUMBER_OF_IMAGES = 1;

    /// <span class="code-SummaryComment"><summary>
</span>    /// Download images from Bing
    /// <span class="code-SummaryComment"></summary>
</span>    public static void DownLoadImages()
    {
        // Make sure destination folder exists
        ValidateDownloadPath();
        XDocument doc = null;
        WebRequest request = null;
        // Because each market can have different images
        // cycle through each of them
        foreach (string market in Markets)
        {
            // Form the URL based on market
            // Since this will be run once per day only 1 image needs to
            // be downloaded
            string url = string.Format(IMG_URL, NUMBER_OF_IMAGES, market);
            request = WebRequest.Create(url);
            using (Stream stream = request.GetResponse().GetResponseStream())
            {
                // Load the stream into and XDocument for processing
                doc = XDocument.Load(stream);
            }

            // Iterate through the image elements
            foreach (XElement image in doc.Descendants("image"))
            {
                SaveImage(image.Element("url").Value);
            }
        }
    }

    /// <span class="code-SummaryComment"><summary>
</span>    /// Save image from the give URL to disk
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="url">URL of image to save</param>
</span>    private static void SaveImage(string url)
    {
        // Images can be duplicated between markets
        // so to avoid duplicates from being downloaded
        // get the unique name based on the image number in the URL
        string filename = GetImageName(url);
        if (!File.Exists(filename))
        {
            // URL is relative so form the absolute URL
            WebRequest request = WebRequest.Create(BING + url);
            using (Stream stream = request.GetResponse().GetResponseStream())
            {
                Image img = Image.FromStream(stream);
                img.Save(filename);
            }
        }
    }

    /// <span class="code-SummaryComment"><summary>
</span>    /// Create filename for image based on URL
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="url">Image URL</param>
</span>    /// <span class="code-SummaryComment"><returns>FQN for saving image to</returns>
</span>    private static string GetImageName(string url)
    {
        // URL is in this format /fd/hpk2/DiskoBay_EN-US1415620951.jpg
        // Extract the image number
        Regex reg = new Regex(@"[0-9]+\w");
        Match m = reg.Match(url);
        // Should now have 1415620951 from above example
        // Create path to save image to
        return string.Format(@"{0}\{1}.jpg", DOWNLOAD_PATH, m.Value);
    }

    /// <span class="code-SummaryComment"><summary>
</span>    /// Check if download path exist and create if necessary
    /// <span class="code-SummaryComment"></summary>
</span>    private static void ValidateDownloadPath()
    {
        if (!Directory.Exists(DOWNLOAD_PATH))
        {
            Directory.CreateDirectory(DOWNLOAD_PATH);
        }
    }
}

With this code, you can create a Windows Service or any other type of application to automate the download process, then set the Windows Desktop backgrounds to use the designated folder.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 5 PinmemberAdrian Grigoriu22-Feb-13 1:13 
QuestionPhp Conversion possible for this code? PinmemberHerit Shah17-Jan-13 12:13 
Hi,
Can anyone convert this C# piece to PhP?
i mean Bing normally updates daily a wallpaper, so i just want to create a function, and when that function is called, it simply returns a string which contains image url. and that can be further used to embed as download button on my website.
 
Can this be accomplished? Confused | :confused: Confused | :confused:
QuestionHow to obtain URL for high-res bing wallpaper from XML file PinmemberSeanKD20-Oct-12 18:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 30 Jan 2011
Article Copyright 2011 by Not Active
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid