2010-09-20 43 views

回答

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

有一個問題:您將失去透明度(對於帶有alpha通道的位圖)。 – sibvic 2015-12-09 09:40:56

5

這是一種替代技術,可以做同樣的事情。被接受的答案有效,但我遇到了具有alpha通道的圖像問題(即使切換到PngBitmapEncoder後)。這種技術也可能更快,因爲它只是在轉換爲兼容像素格式之後進行像素的原始複製。

public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource) 
{ 
     //convert image format 
     var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); 
     src.BeginInit(); 
     src.Source = bitmapsource; 
     src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; 
     src.EndInit(); 

     //copy to bitmap 
     Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
     var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
     src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); 
     bitmap.UnlockBits(data); 

     return bitmap; 
} 
+0

一定要處理'位圖'對象! '使用(位圖位圖=新的位圖(...)){...}' – aholmes 2016-03-11 00:20:58

+0

@aholmes爲什麼人們應該擔心要處理的位圖對象?這是調用者的責任,而不是實施者 – 2016-04-20 05:12:58

+0

我忘了我爲什麼寫這個評論。我想我打算寫'使用(位圖位圖= BitmapFromSource(...)){...}' – aholmes 2016-04-20 20:04:23

相關問題