Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't Initialize WriteableBitmap with BitmapImage

Tags:

c#

silverlight

 BitmapImage img = new BitmapImage(new Uri("somepath",UriKind.Relative));
 WriteableBitmap wbm = new WriteableBitmap(img);

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

like image 442
hashi Avatar asked May 18 '11 06:05

hashi


2 Answers

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);
   };
like image 122
Zabavsky Avatar answered Oct 29 '22 03:10

Zabavsky


If the build action of your image file is set to resource, then the following code will work.

Uri uri = new Uri("/ProjectName;component/Images/image.jpg", UriKind.Relative);
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage img = new BitmapImage();
img.SetSource(resourceInfo.Stream);
WriteableBitmap wbm = new WriteableBitmap(img);

Notice that the resource is accessed by the static method GetResourceStream defined by the application class. Now if you change the build action of the file to Content rather than Resource, you can simplify the Uri sintax considerably.

Uri uri = new Uri("Images/image.jpg", UriKind.Relative);

The difference, in case you are wondering... If you navigate to the Bin/Debug directory of a Visual Studio project and find the XAP file that contains your program, rename it to a ZIP extension. And look inside.

In both cases the bitmap is obviusly stored somewhere within the XAP file.

  • With a Build Action of Resource for the file, it is stored inside the DLL file along with the compiled program.
  • With a Build Action of Content, the file is stored external to the dll file but within the XAP file, and when you rename the XAP file to a ZIP file, you can see the it.
like image 6
Ariel Avatar answered Oct 29 '22 01:10

Ariel