2015-03-31 78 views
1

使用WPF 4.5誤差變換剪貼板圖像

private Bitmap BitmapFromSource(BitmapSource bitmapsource) 
{ 
    Bitmap bitmap; 
    using (var outStream = new MemoryStream()) 
     { 
      BitmapEncoder enc = new BmpBitmapEncoder(); 
      enc.Frames.Add(BitmapFrame.Create(bitmapsource)); 
      enc.Save(outStream); 
      bitmap = new Bitmap(outStream); 
     } 
     return bitmap; 
    } 
} 

再後來:

if (Clipboard.ContainsImage()) 
{ 
    var bitmapSouce = Clipboard.GetImage(); 
    var bitmap = BitmapFromSource(bitmapSouce); 
    var tmp = Path.GetTempFileName(); 
    bitmap.Save(tmp, ImageFormat.Png); 
    ... 

bitmap.Save()引發ExternalException, 「在GDI一般錯誤+」

是它真的很難將剪貼板圖像保存到磁盤?

回答

0

不需要爲了保存而創建WPF BitmapSource中的System.Drawing.Bitmap(即WinForms)。

你還可直接保存到一個FileStream:

private void SaveBitmap(BitmapSource bitmapSource, string fileName) 
{ 
    var enc = new PngBitmapEncoder(); 
    enc.Frames.Add(BitmapFrame.Create(bitmapSource)); 

    using (var outStream = new FileStream(fileName, FileMode.Create)) 
    { 
     enc.Save(outStream); 
    } 
} 

... 

var bitmapSource = Clipboard.GetImage(); 
var tmp = Path.GetTempFileName(); 
SaveBitmap(bitmapSource, tmp);