2010-06-23 110 views
0

我發現下面的例子來下載網頁(串)asynchounously:網上下載圖像異步在.net

let getImage (imageUrl:string) = 
    async { 
     try 
      let req = WebRequest.Create(imageUrl) :?> HttpWebRequest 
      req.UserAgent <- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"; 
      req.Method <- "GET"; 
      req.AllowAutoRedirect <- true; 
      req.MaximumAutomaticRedirections <- 4; 
      let! response1 = req.AsyncGetResponse() 
      let response = response1 :?> HttpWebResponse 
      use stream = response.GetResponseStream() 
      use streamreader = new System.IO.StreamReader(stream) 
      return! streamreader.AsyncReadToEnd() // .ReadToEnd() 
     with 
      _ -> return "" // if there's any exception, just return an empty string 

    } 

它返回一個字符串。但是,我需要以異步的方式下載在線圖像(字節數組)。

任何人都可以給我一些提示?

回答

1

也許你可以用我的回答來解答另一個問題(here)。它向谷歌圖表API請求圖像(URL)並將字節轉換爲位圖。

相關的代碼:

async { 
    let req = HttpWebRequest.Create(..URI HERE..) 
    let! response = req.AsyncGetResponse() 
    return new Bitmap(response.GetResponseStream()) 
} |> Async.RunSynchronously 
+0

爲4.5+ '異步'/ '等待' 版本檢查 - http://stackoverflow.com/questions/11638821/c-sharp-net-4-5-async -多線程 – 2014-09-18 16:40:58

1

您可以直接從流中讀取字節。 StreamReader在字符串上工作。它實際上繼承了TextReader。另外看看使用一個BinaryReader對字節起作用。

(既然你標記它爲C#我會寫在C#我的代碼示例)。

Stream s = response.GetResponseStream() 
MemoryStream memStream = new MemoryStream(); 
int bytesRead; 
byte[] buffer = new byte[0x1000]; 
for (bytesRead = s.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = s.Read(buffer, 0, buffer.Length)) 
{ 
    memStream.Write(buffer, 0, bytesRead); 
} 
s.Close(); 
return memStream.ToArray(); 
-1

可以流轉換爲字節數組像這樣(C#)

byte[] buffer = new byte[16 * 1024]; 
using (MemoryStream ms = new MemoryStream(stream)) 
{ 
    int read; 
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     ms.Write(buffer, 0, read); 
    } 

    var bytes = ms.ToArray(); 
}