2016-10-24 53 views
0

我想通過一個內存流保存一個BitmapImage(System.Windows.Media.Imaging),以便結果可以用來創建一個位圖(System.Drawing)。c#BitmapImage AccessViolationException當保存爲MemoryStream

試圖編碼結果保存到一個MemoryStream,當我斷斷續續得到一個錯誤:

An exception of type 'System.AccessViolationException' occurred in PresentationCore.dll but was not handled in user code 

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 

將MemoryStream的性質似乎表明,一個讀或寫超時發生。下面

WriteTimeout = 'msOut.WriteTimeout' threw an exception of type 'System.InvalidOperationException' 

代碼,錯誤被拋出在保存命令:

  System.Windows.Media.Imaging.CroppedBitmap cbi = new System.Windows.Media.Imaging.CroppedBitmap(bi, new System.Windows.Int32Rect(
      (int)(imageViewBox[2] * imageViewBox[10]), (int)(imageViewBox[3] * imageViewBox[11]), 
      (int)((imageViewBox[4] - imageViewBox[2]) * imageViewBox[10]), (int)((imageViewBox[5] - imageViewBox[3]) * imageViewBox[11]))); 
     newImageSize = new Size(cbi.PixelWidth, cbi.PixelHeight); 

     using (MemoryStream msOut = new MemoryStream()) 
     { 
      System.Windows.Media.Imaging.BmpBitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder(); 
      enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(cbi)); 
      // Throws access violation exception when zoomed on some images. Why? 
      enc.Save(msOut); 
      using (Bitmap temp = new Bitmap(msOut)) 
      { ... 

有問題的圖像一般都是1000像素×500所以不是大規模。 任何想法可能導致這種情況?或者有什麼想法,我可以怎麼做,而不使用內存流的轉換(沒有降低性能?)

回答

0

事實證明,裁剪位圖的原始源bitmapimage(以上代碼中未顯示)導致問題。

該bitmapimage通過URI從磁盤加載。我發現將BitmapCacheOption設置爲Onload而不是None可以消除該錯誤。我猜測圖像在轉換點沒有完全加載。但是,這會使性能降低三倍,這是不幸的。

相關問題