我將兩個庫綁定在一起。一個只給出System.Windows.Media.Imaging.BitmapSource
類型的輸出,另一個只接受System.Drawing.Image
類型的輸入。將System.Windows.Media.Imaging.BitmapSource轉換爲System.Drawing.Image
如何執行此轉換?
我將兩個庫綁定在一起。一個只給出System.Windows.Media.Imaging.BitmapSource
類型的輸出,另一個只接受System.Drawing.Image
類型的輸入。將System.Windows.Media.Imaging.BitmapSource轉換爲System.Drawing.Image
如何執行此轉換?
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;
}
這是一種替代技術,可以做同樣的事情。被接受的答案有效,但我遇到了具有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;
}
有一個問題:您將失去透明度(對於帶有alpha通道的位圖)。 – sibvic 2015-12-09 09:40:56