Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF BitmapSource ImageSource

Tags:

c#

binding

wpf

xaml

I am binding an Image.Source property to the result of the property shown below.

public BitmapSource MyImageSource
{
    get
    {
        BitmapSource source = null;

        PngBitmapDecoder decoder;
        using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                source = decoder.Frames[0];
        }

        return source;
    }
}

For some reason this is failing during the rendering of the image (Deep in the PresentationCore assembly). I am certain the image is not corrupt as I can successfully show the same image w/o the binding

<Image Name="FooImage" Source="/logo.png" />

I have to bind the image source in code because I will eventually be creating the image stream from a base64 string.

Anyone know if this is a bug w/ WPF? or am I doing something incorrectly?

like image 322
user38309 Avatar asked Jan 14 '09 19:01

user38309


2 Answers

The problem was the BitmapCacheOption option, changing to BitmapCacheOption.OnLoad works.

With BitmapCacheOption.None the BitmapSource isn’t decoded until the image is rendered, but the stream with the png in it is already disposed at that point. If you cache OnLoad, it’ll decode right away and cache the results, rather than trying to decode later when the stream no longer exists.

like image 55
user38309 Avatar answered Sep 21 '22 17:09

user38309


Also, have you tried just using a BitmapImage to load the image? It works fine with PNG, BMP, and JPEG.

It's also a specialized type of BitmapSource, so you could just replace your code in your property with this:

BitmapImage img = new BitmapImage(new Uri(@"C:\Temp\logo.png"));
return img;
like image 24
Adrian Avatar answered Sep 21 '22 17:09

Adrian