用BitmapImage讀取圖片遇到的怪問題

摘要:用BitmapImage讀取圖片遇到的怪問題

最近遇到一個奇怪的問題,就是要用BitmapImage讀本機圖片,我把圖片的Build Action設成Content後,然後用BitmapImage就能讀出來,所以我這樣寫..

 

BitmapImage image = new BitmapImage(new Uri("/Images/photo.png", UriKind.Rekative));

 

奇怪的是,image還是null,但是如果我在頁面上有放個Image物件,然後再把Image物件的Source指定給它,這樣image就不會是null,但是,如果是在code直接new個Image物件的話,這方法也是不行,也就是

BitmapImage image = new BitmapImage(new Uri("/Images/photo.png", UriKind.Rekative));
Image imageItem = new Image();
imageItem.Source = image;

以上的image都會是null!後來去goolge了一下,發現有個StreamResourceInfo可以用,所以我就這樣寫了

 

StreamResourceInfo resourceInfo = Application.GetResourceStream(new System.Uri("/Images/photo.png", UriKind.Relative));
BitmapImage image= new BitmapImage();
image.SetSource(resourceInfo.Stream);

 

蝦米?!還是不行!我檢查了一下是否有打錯,發現在Uri那邊的路徑有不一樣,網頁上是打Images/photo.png,而我是打/Images/photo.png,所以我就改過來了

 

StreamResourceInfo resourceInfo = Application.GetResourceStream(new System.Uri("Images/photo.png", UriKind.Relative));
BitmapImage image= new BitmapImage();
image.SetSource(resourceInfo.Stream);

 

終於成功了!!!太感動了!但是.....感覺這應該是bug吧= =?,怎麼要用到這才能讀的到咧,真是奇怪。