C # Metro app How to download an image from the Internet

I added Windows.UI.Xaml.Controls.Image to the canvas. I use HttpClient to make an http call to upload an image. I get the image as a stream and add it as the source of the BitmapImage object, but the image does not load. Can someone please tell me what I'm doing wrong.

The code:

        var httpClient = new HttpClient();
        var content = await httpClient.GetStreamAsync(imageUrl);


            var ras = new InMemoryRandomAccessStream();
            await content.CopyToAsync(ras.AsStreamForWrite());
            bitmap = new BitmapImage();
            bitmap.SetSource(ras);

            myImage.Source = bitmap;
+5
source share
4 answers

I managed to get it to work. Below is the code:

     var httpClient = new HttpClient();            
     var contentBytes = await httpClient.GetByteArrayAsync(uri);                          
     var ims = new InMemoryRandomAccessStream();                
     var dataWriter = new DataWriter(ims);
     dataWriter.WriteBytes(contentBytes);
     await dataWriter.StoreAsync();
     ims.Seek(0);

     bitmap = new BitmapImage();                
     bitmap.SetSource(ims);                

     myImage.Source = bitmap;                
+10
source

I believe this will work:

myImage.Source = new BitmapImage(new Uri(imageUrl));
+5
source

, . URI () .

        using (var response = await HttpWebRequest.CreateHttp(internetUri).GetResponseAsync())
        {
            using (var stream = response.GetResponseStream())
            {
                var desiredName = string.Format("{0}.jpg", uniqueName);
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting);

                using (var filestream = await file.OpenStreamForWriteAsync())
                {
                    await stream.CopyToAsync(filestream);
                    return new Uri(string.Format("ms-appdata:///local/{0}.jpg", uniqueName), UriKind.Absolute);
                }
            }
        }
+2

XAML:

The OS will do some caching, but this does not guarantee that every time you need an image, it will be in the cache. You will need to save it in local storage if you want to.

+1
source

All Articles