2010-09-10 135 views
4

我使用以下代碼來觀看圖像源:爲什麼圖像的流媒體源無法正常工作?

 BitmapImage Art3 = new BitmapImage(); 
     using (FileStream stream = File.OpenRead("c:\\temp\\Album.jpg")) 
     { 
      Art3.BeginInit(); 
      Art3.StreamSource = stream; 
      Art3.EndInit(); 
     } 
     artwork.Source = Art3; 

「藝術品」是其中圖像是應該顯示的XAML對象。該代碼應該不會鎖定圖像,它不會鎖定它,但沒有顯示它,並且默認圖像變成「沒有」......我的猜測是我沒有正確使用該流,並且我的圖像變爲空。幫幫我?

UPDATE:

我現在用下面的代碼,一個朋友向我建議:

 BitmapImage Art3 = new BitmapImage(); 

     FileStream f = File.OpenRead("c:\\temp\\Album.jpg"); 

     MemoryStream ms = new MemoryStream(); 
     f.CopyTo(ms); 
     f.Close(); 

     Art3.BeginInit(); 
     Art3.StreamSource = ms; 
     Art3.EndInit(); 

     artwork.Source = Art3; 

一些奇怪的原因,該代碼返回以下錯誤:

The image cannot be decoded. The image header might be corrupted.

我究竟做錯了什麼?我相信我想加載的圖像不會損壞。

回答

0

您是否嘗試過:

 BitmapImage Art3 = new BitmapImage(); 
     using (FileStream stream = File.OpenRead("c:\\temp\\Album.jpg")) 
     { 
      Art3.BeginInit(); 
      Art3.StreamSource = stream; 
      stream.Flush(); 
      Art3.EndInit(); 
     } 
     artwork.Source = Art3; 
+0

不,那不是我的問題,圖像沒有被加載在所有從源頭抓起,這是我目前的問題是什麼... :( – Thorinair 2010-09-11 07:03:52

1

處置源流將導致的BitmapImage不再顯示任何是流。當您不再使用BitmapImage時,您必須跟蹤流並處理它。

+1

那麼,是什麼我應該注意的是,我開始在C#編程1天前... – Thorinair 2010-09-11 08:37:49

+1

我有這個與BitmapImage相同的問題,並將BitmapImage.StreamSource分配給正在處理的內存流(通過使用)。我不得不刪除用於保存JPG文件我以前認爲我必須使用JpegBitmapDecoder,但這不是必要的。謝謝@rossisdead! – SliverNinja 2011-08-12 04:54:59

8

我設法通過使用下面的代碼來解決這個問題:

 BitmapImage Art3 = new BitmapImage(); 

     FileStream f = File.OpenRead("c:\\temp\\Album.jpg"); 

     MemoryStream ms = new MemoryStream(); 
     f.CopyTo(ms); 
     ms.Seek(0, SeekOrigin.Begin); 
     f.Close(); 

     Art3.BeginInit(); 
     Art3.StreamSource = ms; 
     Art3.EndInit(); 

     artwork.Source = Art3; 

謝謝大家誰試圖幫助我!

+0

謝謝,確保我的內存流重置爲開始在其他地方使用它可以解決我的問題(即拋出與您相同的異常) – Frinavale 2018-02-26 18:57:36

1

這可能是simplier

BitmapImage Art3 = new BitmapImage(new Uri("file:///c:/temp/Album.jpg"));