2012-05-15 53 views
1

這是IM使用的功能,我想將圖像保存在我從硬盤上網站獲得的鏈接中。試圖將圖像保存到硬盤給我錯誤:不支持URI格式

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中使用位圖的底部,但然後我得到錯誤。爲什麼?

+0

打印出來的節點串看到你傳遞給位圖什麼構造函數。我想這是一個URL(來自圖像的src屬性)。 Bitmap ctor需要一個文件名來加載文件,但它不支持URI(如在例外中寫的那樣)。可能您應該使用Web請求從遠程URL下載圖像 –

回答

3

您將不得不首先下載圖像。你不能像這樣保存圖像。使用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

相關問題