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();

1 comments:

Radley Co Tad

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.