2012-08-27 68 views
7

我試圖從網站下載圖像,並創建基於該圖像的位圖。它看起來像這樣:下載圖像並創建位圖

public void test() 
    { 
      PostWebClient client = new PostWebClient(callback); 
      cookieContainer = new CookieContainer(); 
      client.cookies = cookieContainer; 
      client.download(new Uri("SITE")); 
    } 

    public void callback(bool error, string res) 
    { 
      byte[] byteArray = UnicodeEncoding.UTF8.GetBytes(res); 

      MemoryStream stream = new MemoryStream(byteArray); 
      var tmp = new BitmapImage(); 
      tmp.SetSource(stream); 
    } 

我在回調方法的最後一行收到「未指定的錯誤」。有趣的事實是,如果我使用BitmapImage(新的Uri(「SITE」)),它的效果很好......(我不能這樣做,因爲我想從該URL獲取cookie,該圖像是一個jpg PostWebClient類 - >http://paste.org/53413

+0

是否有ByteArray中適當的長度?你可以將byteArray的內容轉儲到一個文件並且映像在那裏? – flayn

+0

在windows-phone .net版本中是否有Image.FromStream? –

+0

@Pinakin Shah no-這就是爲什麼我必須創建位圖和使用image.source =位圖 –

回答

3

你可以試試下面的代碼:

 private Bitmap LoadPicture(string url) 
     { 
      HttpWebRequest wreq; 
      HttpWebResponse wresp; 
      Stream mystream; 
      Bitmap bmp; 

      bmp = null; 
      mystream = null; 
      wresp = null; 
      try 
      { 
       wreq = (HttpWebRequest)WebRequest.Create(url); 
       wreq.AllowWriteStreamBuffering = true; 

       wresp = (HttpWebResponse)wreq.GetResponse(); 

       if ((mystream = wresp.GetResponseStream()) != null) 
        bmp = new Bitmap(mystream); 
      } 
      finally 
      { 
       if (mystream != null) 
        mystream.Close(); 

       if (wresp != null) 
        wresp.Close(); 
      } 
      return (bmp); 
     } 
18

這是從位圖類文檔最簡單的代碼

System.Net.WebRequest request = 
     System.Net.WebRequest.Create(
     "http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif"); 
    System.Net.WebResponse response = request.GetResponse(); 
    System.IO.Stream responseStream = 
     response.GetResponseStream(); 
    Bitmap bitmap2 = new Bitmap(responseStream); 

MSDN link for Bitmap

0

試試這個:

  string url ="http://www.google.ru/images/srpr/logo11w.png" 
      PictureBox picbox = new PictureBox(); 
      picbox.Load(url); 
      Bitmap bitmapRemote = (Bitmap) picbox.Image; 

網址 - 網上的形象,我們創建新實例對象的PictureBox,然後調用不是異步過程從URL,當圖像檢索獲取的圖像作爲位圖圖像加載。 你也可以使用線程與表單一起工作,在其他線程中調用加載並在完成時傳遞刪除方法以檢索圖像。

+3

你能否也添加一個解釋? – Robert

4

最簡單的方法是通過WebClient例如打開一個網絡數據流,並把它傳遞給Bitmapthe constructor

using (WebClient wc = new WebClient()) 
{ 
    using (Stream s = wc.OpenRead("http://hell.com/leaders/cthulhu.jpg")) 
    { 
     using (Bitmap bmp = new Bitmap(s)) 
     { 
      bmp.Save("C:\\temp\\octopus.jpg"); 
     } 
    } 
}