loading the source of a BitmapImage in WPF?

12,469

Solution 1

You'll have to set the BitmapImage.StreamSource property:

BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = _scene.GetStream();
bitmap.EndInit();

If you want to close the stream right after creating the bitmap, you would also have to set the BitmapCacheOption.OnLoad option:

using (Stream stream = _scene.GetStream())
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

Solution 2

You can use the constructor to specify the UriSource

BitmapImage bmp = new BitmapImage(uriSource: new Uri());

Or you can use BitmapImage.StreamSource property to set the StreamSource

Share:
12,469

Related videos on Youtube

xarzu
Author by

xarzu

Why Would I Use My Real Name When "Xarzu" Is so Cool? (I am not really 90 years old either) http://s3.envato.com/files/190523.jpg

Updated on June 04, 2022

Comments

  • xarzu
    xarzu almost 2 years

    In a silverlight app, I have a BitmapImage defined as System.Windows.Media.Imaging.BitmapImage and it as a method called "SetSource" where I can set the source like this:

    BitmapImage bitmap = new BitmapImage();
    System.IO.Stream stream = _scene.GetStream();
    if (stream == null) return;
    bitmap.SetSource(stream);
    

    In a WPF application I have also have a Bitmap image defined as System.Windows.Media.Imaging.BitmapImage but there is no SetSource method. How do I set the source in a WPF app like I do in a Silverlight app?

    Also, it is a stream, not a string. It is not a URI. so "UriSource" method does not work. I tried this:

            System.IO.Stream stream = _scene.GetStream();
            if (stream == null) return;
            BitmapImage bitmap = new BitmapImage();
    
            bitmap.UriSource = new Uri(stream.ToString());
    

    And at runtime, it threw an error tha URI cannot be determined. Is the URI an identifier for the intranet? Are you sure that this is not a silverlight thing? I am doing a WPF application