gpt4 book ai didi

c# - 如何从服务器获取照片并在 Image Control for Wp7 中显示

转载 作者:太空宇宙 更新时间:2023-11-03 14:21:08 24 4
gpt4 key购买 nike

我正在使用下面的代码。我只是不知道为什么它不起作用。错误消息是:关于此的未指定错误: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# - 如何从服务器获取照片并在 Image Control for Wp7 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com