1

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

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,但后来我得到了错误。为什么 ?

4

1 回答 1

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

于 2012-05-15T11:34:04.337 回答