Search code examples
windows-phone-8windows-store-apps

WinRT: How to read images from the pictures library via an URI?


Trying to read an image that is stored in the pictures library via an URI the image is never displayed (in an Image control). Reading the same image via a stream works (assuming the app hat the Picture Library capability declared of course). Reading images from the application's data folder via an URI works.

Does someone know what could be wrong?

Here is how I (unsucessfully) try to read an image via an URI:

var imageFile = (await KnownFolders.PicturesLibrary.GetFilesAsync()).FirstOrDefault();
string imagePath = imageFile.Path;
Uri uriSource = new Uri(imagePath);
var bitmap = new BitmapImage(uriSource);
this.Image.Source = bitmap;

Here is how I sucessfully read the same image via a stream:

var imageFile = (await KnownFolders.PicturesLibrary.GetFilesAsync()).FirstOrDefault();
BitmapImage bitmap;
using (var stream = await imageFile.OpenReadAsync())
{
   bitmap = new BitmapImage();
   await bitmap.SetSourceAsync(stream);
}
this.Image.Source = bitmap;

I need to read the image via URI because this is the fastest way to read images and is async by nature, working perfectly with data binding.


Solution

  • There is no URI for the pictures library. You'll need to get the StorageFile and stream it in.

    The file URI you use doesn't work because the app doesn't have direct access to the PicturesLibrary and so cannot reference items there by path. The StorageFile object provides brokered access to locations that the app doesn't natively have permissions to.