尝试将图像保存到硬盘会给我错误:不支持URI格式

时间:2012-05-15 11:19:09

标签: c#

这是我正在使用的功能,我想将图像保存在我从硬盘上的网站获得的链接中。

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");

      }

 }

在foreach的底部使用Bitmap但是我得到了错误。为什么?

1 个答案:

答案 0 :(得分:3)

您必须先下载图片。您无法保存来自此类URI的图像。使用WebClient获取图像的字节,然后使用该数据创建图像。

这样的事情:

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);
    }

然后,我建议使用System.Drawing.Image.Save将其保存出来:http://msdn.microsoft.com/en-us/library/system.drawing.image.save.aspx