简体   繁体   English

UWP将BitmapImage转换为WriteableBitmap

[英]UWP Converting BitmapImage to WriteableBitmap

Ultimately my goal is to save an image I get from a remote server via http to local storage. 最终,我的目标是将通过http从远程服务器获得的图像保存到本地存储中。

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. 触发ImageDownloaded ,我希望能够将图像另存为.jpg文件。 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. 我已经找到了将图像读入WriteableBitmap方法,但是构造函数需要宽度和高度...但是在获取图像之前我不知道这一点。

What methods can I use to... 我可以使用哪些方法...
1. Obtain the image data in a useful format so I can write it to disk? 1.以有用的格式获取图像数据,以便可以将其写入磁盘?
2. Display it in a Xaml image UIelement? 2.在Xaml图像UIelement中显示它?
3. Be provided with callbacks for DownloadProgress and ImageOpened or downloaded ? 3.是否提供了DownloadProgressImageOpeneddownloaded回调?

I can't believe how tricky this is. 我不敢相信这是多么棘手。

The "writable" in WritableBitmap refers to it being editable (it's not about being writable to disk). WritableBitmap中的“可写”是指它是可编辑的(与可写到磁盘无关)。

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. 为了将下载的图像文件写入磁盘,您不需要BitmapImage或WritableBitmap,只需下载流并将其直接写入磁盘即可。 Then you can also create a BitmapImage from the same stream in order to display it in the XAML Image element. 然后,您还可以从同一流创建一个BitmapImage,以便在XAML Image元素中显示它。

// 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM