【发布时间】:2011-04-14 16:22:34
【问题描述】:
我将两个库捆绑在一起。一个只提供System.Windows.Media.Imaging.BitmapSource 类型的输出,另一个只接受System.Drawing.Image 类型的输入。
如何进行这种转换?
【问题讨论】:
我将两个库捆绑在一起。一个只提供System.Windows.Media.Imaging.BitmapSource 类型的输出,另一个只接受System.Drawing.Image 类型的输入。
如何进行这种转换?
【问题讨论】:
这是做同样事情的另一种技术。接受的答案有效,但我遇到了具有 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;
}
【讨论】:
bitmap对象! using(Bitmap bitmap = new Bitmap(...)) { ... }
bitmap 对象?这是调用者的责任,而不是实施者的责任
using(Bitmap bitmap = BitmapFromSource(...)) {...}
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;
}
【讨论】: