2015-03-31 77 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);