Silverlight : BitmapImage to WriteableBitmap


I can successfully load the following Bitmap like this and display it within an Image control on the view.

var bitmapImage = new BitmapImage
                                UriSource = 
                                    new Uri("../Images/Test.JPG", UriKind.Relative)

However as soon as I add this line to create a WriteableBitmap out of the bitmap,

    var w = new WriteableBitmap(bitmapImage);

I get a Runtime error at the line above: "Object reference not set to an instance of an object."

It seems the BitmapImage creation is delayed, could that be? How should I fix this?


I am now trying this but the openImage seems never to be hit. (even without trying to make it synchronous, it still fails) What is wrong here?

var image = new BitmapImage();
        image.ImageOpened += (sender, args) => resetEventBitmap.Set();
        image.ImageFailed += (o, eventArgs) =>
                                     throw eventArgs.ErrorException;
        image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
        image.UriSource = uri;



Best Solution


Basically, bitmap image has a dependency property "CreateOptions" which, by default, is set to "DelayCreation". This causes the bitmap to be delayed for rendering until after it's needed. Hence, this causes our "object reference not set to an instance of an object" error. To fix this, we have to break the bitmap creation out of the writeablebitmap constructor, change this option, and then put it back in. In this looks like:

    Dim tmpUri As New Uri(yourpath.ToString)
    Dim bmp As New BitmapImage
    bmp.CreateOptions = BitmapCreateOptions.None
    bmp.UriSource = tmpUri
    Dim wb As New WriteableBitmap(bmp)
Related Question