saikamesh
saikamesh

Reputation: 4629

C# Metro app How to load image from web

I have added Windows.UI.Xaml.Controls.Image on a canvas. I am using HttpClient to make http call to download the image. I am getting the image as stream and adding as a source of a BitmapImage object, but the image is not loaded. Can anyone please tell me what I am doing wrong

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;

Upvotes: 5

Views: 4281

Answers (4)

saikamesh
saikamesh

Reputation: 4629

I managed to get it working. 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;                

Upvotes: 10

Pedro Alonso
Pedro Alonso

Reputation: 283

you can do that using XAML:

The OS will do some caching, but that doesn't guarantee that it each time that you need the image it will be in the cache. You'll need to save it to local storage if you want to achieve that.

Upvotes: 1

Jennifer Marsman - MSFT
Jennifer Marsman - MSFT

Reputation: 5225

Here is a code snippet that I've used to successfully download images from the web. It copies the image to local storage and returns a URI to the new (local) location.

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

Upvotes: 2

user1567095
user1567095

Reputation: 480

I believe this will work:

myImage.Source = new BitmapImage(new Uri(imageUrl));

Upvotes: 5

Related Questions