MX D
MX D

Reputation: 2485

How to load all images from a URL?

I am trying to get all image files from a site, and show these in a gallery. So people can scroll through all the images like I did here with localy stored images.

After some searching I found this example but it was only meant for single image loading, and not for all images within this online directory, using the following.

//Location of image directory with xxx images.  
string directoryUrl = "http://www.foo.com/bar"; 

void DownloadTextures(string url)
{
    try
    {
        WebRequest req = WebRequest.Create(url);
        WebResponse response = req.GetResponse();
        Stream stream = response.GetResponseStream();
    }
    catch ( Exception e)
    {
        print("stuff went wrong: " +e)
    }
}

So how can I get all images out of online directory, and is this the right approach to get that done?

ps. It is all done in the unity engine, which has some limitations.

Upvotes: 0

Views: 3381

Answers (2)

Pavlo
Pavlo

Reputation: 397

As regular expressions are really bad way to parse html, I believe it's better to use some library for your purposes. The best one I heard about is HtmlAgilityPack

The example how to parse images using it you can find here

Then you can use WebClient.DownloadFile method to download images like this. Please, note that images links could be relative, so you need to handle it too.

Upvotes: 1

Vajura
Vajura

Reputation: 1132

using System.Net;
using System.IO;
using System.Text.RegularExpressions;
private void Form1_Load(object sender, EventArgs e)
{
    string urlAddress = "http://melloniax.com/css/style.css";
    string urlBase = "http://melloniax.com";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string data = "";
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream receiveStream = response.GetResponseStream();
        StreamReader readStream = null;
        if (response.CharacterSet == null)
            readStream = new StreamReader(receiveStream);
        else
            readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
        data = readStream.ReadToEnd();
        response.Close();
        readStream.Close();
    }
    MatchCollection matches = Regex.Matches(data, @"\(..(?<link>[^.]*(\.jpg|\.png|\.gif)) *\)");
    for (int a = 0; a < matches.Count; a++)
        MessageBox.Show(urlBase + matches[a].Groups["link"].Value);
}

This works for your example, if you need anything else like how to actualy save the imgs from the url you got tell me.

Upvotes: 1

Related Questions