UWP Converting BitmapImage to WriteableBitmap

1k Views Asked by At

Ultimately my goal is to save an image I get from a remote server via http to local storage.

I read it like this

BitmapImage^ im = ref new BitmapImage();
im->CreateOptions = BitmapCreateOptions::IgnoreImageCache;
im->DownloadProgress += ref new DownloadProgressEventHandler(this, &Capture::ShowDownloadProgress);
im->ImageOpened += ref new RoutedEventHandler(this, &Capture::ImageDownloaded);
im->UriSource = ref new Uri(URL);

When ImageDownloaded is triggered I want to be able to save the image as a .jpg file. I already have write permission to the destination folder.

I've found approaches that read the image into a WriteableBitmap however the constructor requires the width and height... but I do not know this prior to getting the image.

What methods can I use to...
1. Obtain the image data in a useful format so I can write it to disk?
2. Display it in a Xaml image UIelement?
3. Be provided with callbacks for DownloadProgress and ImageOpened or downloaded?

I can't believe how tricky this is.

1

There are 1 best solutions below

2
On BEST ANSWER

The "writable" in WritableBitmap refers to it being editable (it's not about being writable to disk).

In order to write the downloaded image file to disk you don't need BitmapImage or WritableBitmap, you can just download the stream and write it directly to disk. Then you can also create a BitmapImage from the same stream in order to display it in the XAML Image element.

// download image and write to disk
Uri uri = new Uri("https://assets.onestore.ms/cdnfiles/external/uhf/long/9a49a7e9d8e881327e81b9eb43dabc01de70a9bb/images/microsoft-gray.png");
StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync("microsoft-gray.png", uri, null);
await file.CopyAsync(ApplicationData.Current.LocalFolder, "microsoft-gray.png", NameCollisionOption.ReplaceExisting);

// create a bitmapimage and display in XAML
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
BitmapImage bitmap = new BitmapImage();
await bitmap.SetSourceAsync(stream);
imageElement.Source = bitmap;