【问题标题】:UWP Converting BitmapImage to WriteableBitmapUWP 将 BitmapImage 转换为 WriteableBitmap
【发布时间】:2018-02-19 01:42:20
【问题描述】:

最终我的目标是将我通过 http 从远程服务器获取的图像保存到本地存储。

我是这样读的

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

ImageDownloaded 被触发时,我希望能够将图像保存为 .jpg 文件。我已经拥有目标文件夹的写入权限。

我找到了将图像读入WriteableBitmap 的方法,但是构造函数需要宽度和高度...但在获取图像之前我不知道这一点。

我可以使用哪些方法...
1. 获取有用格式的图像数据,以便我可以将其写入磁盘?
2. 在 Xaml 图像 UIelement 中显示它?
3. 提供DownloadProgressImageOpeneddownloaded 的回调?

我不敢相信这是多么棘手。

【问题讨论】:

    标签: xaml uwp c++-cx


    【解决方案1】:

    WritableBitmap 中的“可写”是指它是可编辑的(不是可写到磁盘)。

    为了将下载的图像文件写入磁盘,您不需要 BitmapImage 或 WritableBitmap,您只需下载流并将其直接写入磁盘。然后,您还可以从同一流创建 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;
    

    【讨论】:

    • 我看不到报告下载 CreateStreamedFileFromUriAsync 进度的方法。在图像较大且用户连接速度较慢的情况下,这是一个很好的反馈,表明它仍在工作。
    • 也可以使用HttpClient下载流(并观察进度),然后创建StorageFile:docs.microsoft.com/en-us/uwp/api/windows.web.http.httpclient
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多