开发者

How to get a photo from Server and display it in Image Control for Wp7

开发者 https://www.devze.com 2023-02-18 17:29 出处:网络
I am using the below code. I just dont know why it is not working. The error msg is : Unspecified error on this : bmp.SetSource(ms).

I am using the below code. I just dont know why it is not working. The error msg is : Unspecified error on this : bmp.SetSource(ms).

I am not familiar with HttpWebRequest for Wp7. Would appreciate your help to solve this problem. Thanks.

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);
        }
   }


Is it necessary to copy the response stream to a byte array and then to a MemoryStream? If not, you can just do the following:

    Stream myStream = response.GetResponseStream();
    Deployment.Current.Dispatcher.BeginInvoke(() => {
        BitmapImage bmp = new BitmapImage();
        bmp.SetSource(myStream);
        image1.Source = bmp;
    });

If you have to do the copy for some reason, you will need to fill the buffer in a loop:

    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
    });

Second part adapted (slightly) from C# bitmap images, byte arrays and streams!.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号