Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 755
saikamesh Avatar asked Aug 01 '12 12:08

saikamesh


4 Answers

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;                
like image 123
saikamesh Avatar answered Oct 04 '22 22:10

saikamesh


I believe this will work:

myImage.Source = new BitmapImage(new Uri(imageUrl));
like image 38
user1567095 Avatar answered Oct 04 '22 20:10

user1567095


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);
                }
            }
        }
like image 39
Jennifer Marsman - MSFT Avatar answered Oct 04 '22 22:10

Jennifer Marsman - MSFT


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.

like image 28
Pedro Alonso Avatar answered Oct 04 '22 20:10

Pedro Alonso