繁体   English   中英

如何将BitmapFrame转换为BitmapImage

[英]How to convert BitmapFrame into BitmapImage

我的程序使用一些WPF API来处理文件夹中的图像。 我需要从图像中解析EXIF数据(如果有)以便获取DateTimeOriginal属性的值。 我一直在使用BitmapImageMemoryStream加载图像,但是我需要一个BitmapFrame对象来获取BitmapMetadata对象。

这是在要求获得DateTimeOriginal EXIF属性之前的原始代码:

BitmapImage src = new BitmapImage();
try {
    using ( MemoryStream memoryStream = new MemoryStream( snapshot.ImageData ) ) {
        src.BeginInit();
        src.CacheOption  = BitmapCacheOption.OnLoad;
        src.StreamSource = memoryStream;
        src.EndInit();
    }
} catch ( NotSupportedException ex ) {
    . . .
}

现在,要获取BitmapFrame ,我需要创建一个BitmapDecoder并使用Frames[0]属性。 因此,我在using语句之后添加了以下内容:

BitmapDecoder decoder = BitmapDecoder.Create( memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad );

这将解码位图并获取第一个Frame,这很酷。 我仍然需要创建BitmapImage 我可以通过将MemoryStream's位置重新设置为开始并保留已经存在的代码来做到这一点,但这将再次解码同一张图像。

有没有一种方法可以将BitmapFrame转换为BitmapImage 我以为我可以将BitmapFrame转换为BitmapSource对象,然后设置BitmapImage's Source Source属性,但是BitmapImage类似乎没有Source属性。

这可能吗? 如果是这样,怎么做?

无需进行此转换。 BitmapImage MSDN页面中的“备注”部分显示:

BitmapImage主要是为了支持可扩展应用程序标记语言(XAML)语法而存在的,并引入了BitmapSource未定义的其他位图加载属性。

使用位图时,您的应用程序通常应始终使用BitmapSourceImageSource基类。 例如,当您分配WPF Image控件的Source属性时,可以使用从ImageSource派生的任何类型的实例,因为这是Source属性的类型。

因此,您可以直接使用BitmapFrame因为它也源自ImageSource

var bitmap = BitmapFrame.Create(
    memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

image.Source = bitmap;

暂无
暂无

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

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