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."
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);
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With