2016-12-12 53 views
1

我嘗試保存BitmapSource時遇到問題。我也在GDI +中出現錯誤,或者該文件正在被另一個進程使用。保存BitmapSource時出錯

的梅索德到BitmapImage的保存

protected override void Save() 
{ 
    Bitmap bitmap = Thumbnail.ToBitmap(); 

    if (Angle % 360 == 0) 
     bitmap.RotateFlip(RotateFlipType.RotateNoneFlipNone); 
    else if (Angle % 270 == 0) 
     bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone); 
    else if (Angle % 180 == 0) 
     bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); 
    else if (Angle % 90 == 0) 
     bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone); 

    bitmap.Save(Objects[0].FilePath); 
    Objects[0].RaisePropertyChanged("Thumbnail"); 
} 

的BitmapSource爲位圖轉換

public static Bitmap ToBitmap(this BitmapSource bitmapsource) 
{ 
    using (MemoryStream stream = new MemoryStream()) 
    { 
     BitmapEncoder enc = new BmpBitmapEncoder(); 
     enc.Frames.Add(BitmapFrame.Create(bitmapsource)); 
     enc.Save(stream); 

     using (var tempBitmap = new Bitmap(stream)) 
     { 
      return new Bitmap(tempBitmap); 
     } 
    } 
} 

用來保存來自一個get屬性

public BitmapSource Image 
{ 
    get { return new BitmapImage(new Uri(FilePath)); } 
} 

「縮略圖」該文件的縮略圖也用於視圖中。我用windows shell API獲得它。

public static BitmapSource GetThumbnail(this string This, BitmapSize size = BitmapSize.Large) 
{ 
    if (ShellObject.IsPlatformSupported) 
    { 
     ShellObject shellitem = ShellObject.FromParsingName(This); 

     try 
     { 
      if (size == BitmapSize.Small) 
       return shellitem.Thumbnail.SmallBitmap.ToBitmapSource(); 
      else if (size == BitmapSize.Medium) 
       return shellitem.Thumbnail.MediumBitmap.ToBitmapSource(); 
      else if (size == BitmapSize.Large) 
       return shellitem.Thumbnail.LargeBitmap.ToBitmapSource(); 
      else 
       return shellitem.Thumbnail.ExtraLargeBitmap.ToBitmapSource(); ; 
     } 
     catch (Exception) 
     { 
      return null; 
     } 
    } 

     return null; 
    } 

是否有任何解決方案?

感謝 維姆

+0

正是你得到這個例外? –

+0

位圖圖像是文件的加載器,它將圖像源保持在打開狀態,如果禁用了緩存,那麼它應該在加載後關閉數據源 – MikeT

+0

該錯誤發生在bitmap.Save(...) –

回答

0

儘量用在哪一行Application.current.dispatcher

Application.current.dispatcher(()=>Save()); 
+0

位圖圖像具有Dispatcher屬性,最好使用該應用程序的 – MikeT