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

      }

 }

ビットマップを使用しているforeachimの下部にありますが、エラーが発生しています。なぜ ?

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 に答える