Thursday, July 31, 2008

.Net FormatConvertedBitmap Crashes With Local Resource

When setting a BitmapImage to your Resource item (those marked as Resource) on a XAML app, that works out just fine with:

BitmapImage bm = new BitmapImage();

bm.BeginInit();

bm.UriSource = new Uri("/Images/test.png", UriKind.Relative);

bm.EndInit();


However, using the follow code gives you an error about finding the Url:

FormatConvertedBitmap newBitmap = new FormatConvertedBitmap();

newBitmap.BeginInit();

newBitmap.Source = (BitmapSource)bm;

newBitmap.DestinationFormat = PixelFormats.Gray8;

newBitmap.EndInit();


I found a post detailing the solution for now with this bug that will hopefully be fixed. You must specify an Absolute Url in your BitmapImage that refers directly to the packaged resource. Then the above code with the FormatConvertedBitmap will work correcctly.

BitmapImage bm = new BitmapImage();

bm.CacheOption = BitmapCacheOption.OnLoad;

bm.BeginInit();

bm.UriSource =

new Uri("pack://application:,,,/Images/test.png", UriKind.Absolute);

bm.EndInit();

0 comments: