将图像加载到writeablebitmap中

kiz*_*ore 5 c# silverlight writeablebitmap

所以我试图将图像加载到WriteableBitmap但我得到一个NullReferenceException.无法弄清楚为什么因为我以前认为这曾经工作过

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

而已.我将汽车图像作为我项目中的资源.它工作正常,因为我可以创建一个Image控件并将其源设置为BitmapImage并显示它.谢谢

CC *_*Inc 12

从其他SO问题看,似乎你得到空引用异常的原因是BitmapImage.CreateOptions属性的默认值是BitmapCreateOptions.DelayCreation.您可以将其设置为BitmapCreateOptions.NoneWriteableBitmap在加载图像后创建:

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

使用该代码,WritableBitmap将等待BitmapImage加载,然后它将被分配给WritableBitmap.