我正在使用以下代码。我只是不知道为什么它不起作用。错误消息是:对此未指定错误:bmp.SetSource(ms)。
我对Wp7的HttpWebRequest不熟悉。感谢您为解决此问题所提供的帮助。谢谢。
enter code here
private void LoadPic()
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"http://xxxxxx/MyImage.jpg");
NetworkCredential creds = new NetworkCredential("Username", "Pwd");
req.Credentials = creds;
req.Method = "GET";
req.BeginGetResponse(new AsyncCallback(GetStatusesCallBack), req);
}
public void GetStatusesCallBack(IAsyncResult result)
{
try
{
HttpWebRequest httpReq = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)httpReq.EndGetResponse(result);
Stream myStream = response.GetResponseStream();
int len = (int)myStream.Length;
byte[] byt = new Byte[len];
myStream.Read(byt, 0, len);
myStream.Close();
MemoryStream ms = new MemoryStream(byt);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(ms);
image1.Source = bmp;
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
最佳答案
是否有必要将响应流复制到字节数组,然后再复制到MemoryStream?如果没有,您可以执行以下操作:
Stream myStream = response.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() => {
BitmapImage bmp = new BitmapImage();
bmp.SetSource(myStream);
image1.Source = bmp;
});
如果由于某种原因必须进行复制,则需要循环填充缓冲区:
Stream myStream = response.GetResponseStream();
int contentLength = (int)myStream.Length;
byte[] byt = new Byte[contentLength];
for (int pos = 0; pos < contentLength; )
{
int len = myStream.Read(byt, pos, contentLength - pos);
if (len == 0)
{
throw new Exception("Upload aborted.");
}
pos += len;
}
MemoryStream ms = new MemoryStream(byt);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// same as above
});
第二部分(略)来自C# bitmap images, byte arrays and streams!。
关于c# - 如何从服务器获取照片并将其显示在Wp7的Image Control中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5365975/