Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Phone 7 download image and display it

I'm a newbie to windows phone platform, and I'm trying to build a simple application that reads an image url from textbox, and upon a download button click downloads this image to the phone memory and then displays it in an Image control.

this code is written when the user clicks on the download button:

string url = "http://some-url-image-name.jpg";
WebClient client = new WebClient();
client.DownloadStringCompleted += DownloadCompleted;
client.DownloadStringAsync(new Uri(url));

and this is the DownloadStringCompleted event handler:

private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            string result = e.Result;
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
            {
                var bi = new BitmapImage();
                bi.SetSource(stream);
                image.Source = bi;
            }
        }

it is giving an 'unspecified error' exception. How to solve it? or does anybody know a better approach to do this ?

Another question, what is the nature of e.Result? is it the downloaded image content as a string or the path to something or what ?

Thanks

like image 600
NadaNK Avatar asked Dec 04 '12 10:12

NadaNK


1 Answers

A picture is binary content, not a string. You have either to use WebClient.OpenReadAsync (instead of DownloadStringAsync), or set directly your url as source for your BitmapImage:

var bi = new BitmapImage(new Uri("http://some-url-image-name.jpg"));
like image 140
Kevin Gosse Avatar answered Nov 02 '22 07:11

Kevin Gosse