Daniel Lip
Daniel Lip

Reputation: 11319

Trying to save images to hard disk give me error: URI formats are not supported

This is the function im using and I want to save the images in the links i got from the website on my hard disk.

public void GetAllImages()
{

  // Bing Image Result for Cat, First Page
  string url = "http://www.bing.com/images/search?q=cat&go=&form=QB&qs=n";


  // For speed of dev, I use a WebClient
   WebClient client = new WebClient();
   string html = client.DownloadString(url);

   // Load the Html into the agility pack
   HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
   doc.LoadHtml(html);

   // Now, using LINQ to get all Images
   /*List<HtmlNode> imageNodes = null;
   imageNodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//img")
                              where node.Name == "img"
                              && node.Attributes["class"] != null
                              && node.Attributes["class"].Value.StartsWith("sg_t")
                              select node).ToList();*/

   var imageLinks = doc.DocumentNode.Descendants("img")
        .Where(n => n.Attributes["class"].Value == "sg_t")
        .Select(n => HttpUtility.ParseQueryString(n.Attributes["src"].Value["amp;url"])
        .ToList();





   foreach (string node in imageLinks)
     {
      y++;
      //Console.WriteLine(node.Attributes["src"].Value);
      richTextBox1.Text += node + Environment.NewLine;
      Bitmap bmp = new Bitmap(node);
      bmp.Save(@"d:\test\" + y.ToString("D6") + ".jpg");

      }

 }

In the bottom in the foreach im using Bitmap but then im getting the error. why ?

Upvotes: 1

Views: 1159

Answers (1)

Chris Dworetzky
Chris Dworetzky

Reputation: 950

You're going to have to download the images first. You can't save images from URIs like that. Get the bytes for the image using WebClient and then create your image using that data.

Something like this:

private System.Drawing.Image GetImage(string URI)
    {
        WebClient webClient = new WebClient();
        byte[] data = webClient.DownloadData(URI);
        MemoryStream memoryStream = new MemoryStream(data);
        return System.Drawing.Image.FromStream(memoryStream);
    }

Then, I would suggest using System.Drawing.Image.Save to save it out: http://msdn.microsoft.com/en-us/library/system.drawing.image.save.aspx

Upvotes: 3

Related Questions