Tony Vitabile
Tony Vitabile

Reputation: 8614

How to convert BitmapFrame into BitmapImage

My program uses some WPF APIs to process images in a folder. I need to parse EXIF data from the images if there is any in order to get the value of the DateTimeOriginal property. I've been using a BitmapImage to load the image from a MemoryStream, but I need a BitmapFrame object to get at the BitmapMetadata object.

Here's my original code before I was given the requirement to get the DateTimeOriginal EXIF property:

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 ) {
    . . .
}

Now, to get the BitmapFrame, I need to create a BitmapDecoder and use the Frames[0] property. So I added the following right after the using statement:

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

This decodes the bitmap and gets the first Frame, which is cool. I still need to create the BitmapImage. I can do that by resetting the MemoryStream's position back to the beginning and keeping the code that's already there, but this will decode the same image a second time.

Is there a way I can convert the BitmapFrame into a BitmapImage? I thought I would cast the BitmapFrame into a BitmapSourceobject and then set the BitmapImage's Source propert, but the BitmapImage class doesn't seem to have a Source property.

Is this possible? If so, how is it done?

Upvotes: 2

Views: 13950

Answers (1)

Clemens
Clemens

Reputation: 128116

There should be no need for this conversion. The Remarks section in the BitmapImage MSDN page says:

BitmapImage primarily exists to support Extensible Application Markup Language (XAML) syntax and introduces additional properties for bitmap loading that are not defined by BitmapSource.

When using bitmaps, your application should usually always use the BitmapSource or ImageSource base classes. For example when you assign the Source property of the WPF Image control, you can use an instance of any type derived from ImageSource, because that is the type of the Source property.

So you could directly use a BitmapFrame because it also derives from ImageSource:

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

image.Source = bitmap;

Upvotes: 5

Related Questions