我想讀網站上的PNG文件的原始二進制並將其存儲到一個byte [],到目前爲止,我有這樣的事情:使用的HttpWebRequest從網站獲得的圖像爲byte []
Uri imageUri = new Uri("http://www.example.com/image.png");
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(imageUri);
using (HttpWebResponse imgResponse = (HttpWebResponse)imgRequest.GetResponse())
{
using (BinaryReader lxBR = new BinaryReader(imgResponse.GetResponseStream()))
{
using (MemoryStream lxMS = new MemoryStream())
{
lnBuffer = lxBR.ReadBytes(1024);
while (lnBuffer.Length > 0)
{
lxMS.Write(lnBuffer, 0, lnBuffer.Length);
lnBuffer = lxBR.ReadBytes(1024);
}
lnFile = new byte[(int)lxMS.Length];
lxMS.Position = 0;
lxMS.Read(lnFile, 0, lnFile.Length);
}
}
}
但我不能在Silverlight上使用GetResponse
,因爲它不是異步的(我認爲這是原因),所以我應該使用BeginGetResponse
,但我不完全清楚如何去解決這個問題。這是我到目前爲止有:
HttpWebResponse imgResponse = (HttpWebResponse)imgRequest.BeginGetResponse(new AsyncCallback(WebComplete), imgRequest);
using (imgResponse)
{
using (BinaryReader lxBR = new BinaryReader(imgResponse.GetResponseStream()))
{
/*Same*/
}
}
和
void WebComplete(IAsyncResult a)
{
HttpWebRequest req = (HttpWebRequest)a.AsyncState;
HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(a);
//...? Do I need something else here?
}
有人可以解釋我一點點如何使用BeginGetResponse
財產,我怎麼使用的AsyncCallback。 謝謝!
注: 我是新來的Silverlight和我一直跟隨在計算器上的教程和借款從這裏其他的反應: (stackoverflow responce) what I need to do but not in silverlight
這是有效的Silverlight代碼?
HttpWebResponse imgResponse = (HttpWebResponse)imgRequest.BeginGetResponse(new AsyncCallback(WebComplete), imgRequest);
爲什麼存儲流?一旦擁有它,你會怎麼做? – AnthonyWJones 2010-08-04 16:57:11
我只需要圖像的字節來修改它們,然後從它們中創建一個BitmapImage。如果內存流不簡化我的工作,那麼我不會使用它(說實話,我不知道什麼是內存流) – david 2010-08-04 18:07:31