我正在使用以下代码。我只是不知道它为什么不起作用。错误消息是:未指定错误: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);
}
}
答案 0 :(得分:1)
是否有必要将响应流复制到字节数组,然后复制到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!。