Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load image into writeablebitmap

So Im trying trying to load an image into a WriteableBitmap but I'm getting a NullReferenceException. Can't figure out why because I think this used to work before

BitmapImage b = new BitmapImage(new Uri(@"images/Car.jpg", Urikind.Relative)); WriteableBitmap wb = new WriteableBitmap(b);

thats it. I have the car image as a resource in my project. It works fine as I can create a Image control and set its source to the BitmapImage and display it. Thanks

like image 238
kiznore Avatar asked Sep 02 '12 22:09

kiznore


1 Answers

As seen from other SO questions, it seems that the reason you get the null reference exception is that BitmapImage.CreateOptions Property default value is BitmapCreateOptions.DelayCreation. You can set it to BitmapCreateOptions.None and create WriteableBitmap after image loaded:

BitmapImage img = new BitmapImage(new Uri("somepath",UriKind.Relative));
img.CreateOptions = BitmapCreateOptions.None;
img.ImageOpened += (s, e) =>
   {
       WriteableBitmap wbm = new WriteableBitmap((BitmapImage)s);
   };

Using that code, the WritableBitmap will wait until the BitmapImage is loaded, and then it will be able to be assigned to the WritableBitmap.

like image 50
CC Inc Avatar answered Oct 07 '22 08:10

CC Inc