Search code examples
c#uwpwin-universal-app

BitmapImage to StorageFile in UWP


I have a BitmapImage by doing this:

var bitmap = new BitmapImage(new Uri(url, UriKind.Absolute))

But, because I am working with a Cortana App, I need to use StorageFile as the image type (very stupid imo, but that is how it is)

So, how can I transform that bitmap into the StorageFile I need, or how can I download an image through an URL into a StorageFile, because

StorageFle.GetFileFromApplicationUriAsync(Uri uri)

keeps popping an exception of "Value does not fall within the specified range"

Any help would be very much appreciated, thanks!


Solution

  • StorageFle.GetFileFromApplicationUriAsync is used to get app resource.

    To download a remote Uri as a StorageFile, use StorageFile.CreateStreamedFileFromUriAsync.

    var path = "https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png";
    var file = await StorageFile.CreateStreamedFileFromUriAsync(Path.GetFileName(path), 
        new Uri(path), null);
    

    You can also save the file to disk check if it is downloaded correctly.

    await file.CopyAsync(ApplicationData.Current.LocalFolder);