如何在Windows 10的通用应用程序中将BitmapImage转换为WriteableBitmap?

Zen*_*phe 2 converter bitmapimage win-universal-app uwp-xaml

我正在使用MVVM在Windows 10上实现通用Windows应用程序.我有一个文件选择器,允许我选择一个图像.该图像显示在图像控件中.Image Control的源绑定到视图模型中的属性.此属性是一个字节数组.我需要一个转换器来转换字节数组中的BitmapImage.我已经阅读了很多东西,但找不到合适的东西.我在https://writeablebitmapex.codeplex.com/上找到了有趣的东西 但是如果我想使用这个包我需要一个WriteableBitmap而不是BitmapImage.预先感谢您的帮助.

Igo*_*lic 5

您可以直接从文件将图像加载到WriteableBitmap对象.

var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".jpg");
var result = await filePicker.PickSingleFileAsync();

if (result != null)
{
    using (IRandomAccessStream stream = await result.OpenAsync(FileAccessMode.Read))
    {
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
        WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
        bmp.SetSource(stream);

        // show the image in the UI if you want.
        MyImage.Source = bmp;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样你就有了WriteableBitmap,你可以使用WriteableBitmapEx库.

  • 知道如何在不通过文件选择器的情况下实现这一目标吗? (4认同)