今天写代码的时候,遇到需要将BitmapImage转化为WriteableBitmap,自己果断写下如下代码。结果调试的时候每次都报错。

BitmapImage bitmapImage = new BitmapImage(new Uri("/p_w_picpaths/test.png",UriKind.Relative));WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);

  自己尝试设置图片的属性,无论是resource还是content也都不行,地址也是绝对相对都换过,还是不行。

  最后google到发现bitmapImage原来是异步加载图片,也就说我创建writeablebitmap的时候bitmapp_w_picpath还没有加载完成,所以报错。

  于是就有了

///do something...
            Uri url = new Uri("/Img/1.png", UriKind.Relative);            BitmapImage bitmapImage = new BitmapImage();            bitmapImage.CreateOptions = BitmapCreateOptions.None;            bitmapImage.ImageOpened += bitmapImage_ImageOpened;            bitmapImage.UriSource = url;            bitmapImage.ImageFailed += bitmapImage_ImageFailed;} void bitmapImage_ImageOpened(object sender, RoutedEventArgs e)        {            WriteableBitmap wb = new WriteableBitmap(sender as BitmapImage);            ///do something...
        }

  当然也可以这么写:

Uri url = new Uri("/Img/1.png", UriKind.Relative);BitmapImage bitmapImage = new BitmapImage();bitmapImage.CreateOptions = BitmapCreateOptions.None;bitmapImage.ImageOpened +=(o,args)=>
   {
WriteableBitmap wb = new WriteableBitmap(o as BitmapImage);
///do something ...
   };
bitmapImage.UriSource
= url;

  本文来自jecofang的博客,原文地址:http://www.cnblogs.com/jecofang/archive/2012/06/28/2566537.html