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;
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;
I believe this will work:
myImage.Source = new BitmapImage(new Uri(imageUrl));
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);
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With