如何保存BitmapImage WinRT

我有BitmapImage:

BitmapImage image = new BitmapImage(); image.SetSource(memStream); 

我想将图像保存到磁盘以便将来查看。 我找不到一个如何做到这一点的工作示例? 第二个问题。 我需要获得像素的颜色(如: Color cl=image.GetColorPixel(X,Y) ),我该怎么做? 谢谢!

这是我之前在网络上发现的代码。 我不确定,但如果我正确的话,它来自sdk示例或winrt博客

这一切都归结为WritabelBitmap图像(就像已发布的其他图像一样),创建一个解码器并将其推送到流中。

  ///  /// ///  ///  ///  ///  ///  public static async Task SaveToFile( this WriteableBitmap writeableBitmap, IStorageFile outputFile, Guid encoderId) { try { Stream stream = writeableBitmap.PixelBuffer.AsStream(); byte[] pixels = new byte[(uint)stream.Length]; await stream.ReadAsync(pixels, 0, pixels.Length); using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels); await encoder.FlushAsync(); using (var outputStream = writeStream.GetOutputStreamAt(0)) { await outputStream.FlushAsync(); } } } catch (Exception ex) { string s = ex.ToString(); } } 

您可以通过以下方式保存BitmapImage。

 Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile sampleFile = await localFolder.CreateFileAsync("image.png"); await FileIO.WriteBytesAsync(sampleFile, bytes); 

image.png将保存在Application的LocalFolder中。

希望能帮助到你!

  • Binaya Raj Shrestha

您无法保存或修改BitmapImage 。 您需要使用WriteableBitmap 。 如果你真的别无选择,只能从BitmapImage开始 – 检查它的UriSource属性,或者再次下载相同的图像,或者加载一个与起始BitmapImage具有相同内容的WriteableBitmap 。 请注意,在某些情况下, UriSource可能为null – 即使通过为其提供URI来加载BitmapImage – 也可以手动重置或通过将CacheMode设置为使用给定BitmapImage作为其SourceImage上的BitmapCache来重置。

看看这个链接。 有一个片段显示了WriteableBitmap的一些操作http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.aspx

这个例子是阅读,但写作应该不难。

要遍历像素,请查看PixelData属性。

如果你试图从你的xaml中取出一个ui元素并将其保存为图像,那就不幸了。 在wpf中,有一个可写位图的方法,它将UIelement作为参数但在Windowsapp store中不存在。

您可以使用DirectX,但这是一种非常复杂的方法。 商店中的大多数绘图应用程序都使用JavaScript,因为它更容易进行保存。