使用Visual C#2010,我试图从Windows Kinect收到的帧中编写.avi文件。使用BitmapEncoder和PngBitmapEncoder(保存到流)可以很容易地保存帧作为.png文件,但我不能自行决定将这些图像添加到此处提供的VideoStream中: http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library 因为我需要能够将RenderTargetBitmap或DrawingVisual转换为System.Drawing.Bitmap。
我发现了做类似事情的示例代码,但他们似乎都希望实例化Visual Studio告诉我的Image类是抽象的,无法实例化。
我绕圈而不到任何地方。
我只想做这样的事情:
...
renderBitmap.Render(dv);
Bitmap bmp=new Bitmap(dv);
VideoStream aviStream=aviManager.AddVideoStream(true,60,bmp);
...
但Bitmap没有有用的构造函数可以让我从dv(DrawingVisual)到bmp。 :(
这3行来自这个片段:
var renderBitmap=new RenderTargetBitmap(colorWidth,colorHeight,96.0,96.0,PixelFormats.Pbgra32);
DrawingVisual dv=new DrawingVisual();
using(DrawingContext dc=dv.RenderOpen())
{
VisualBrush backdropBrush=new VisualBrush(Backdrop);
dc.DrawRectangle(backdropBrush,null,new Rect(0,0,colorWidth,colorHeight));
VisualBrush colorBrush=new VisualBrush(MaskedColor);
dc.DrawRectangle(colorBrush,null,new Rect(0,0,colorWidth,colorHeight));
VisualBrush watermarkBrush=new VisualBrush(Watermark);
dc.DrawRectangle(watermarkBrush,null,new Rect(colorWidth-96,colorHeight-80,64,48));
}
renderBitmap.Render(dv);
Bitmap bmp=new Bitmap(dv);
VideoStream aviStream=aviManager.AddVideoStream(true,60,bmp);
答案 0 :(得分:2)
使用RenderTargetBitMap的结果是WPF BitMapSource它没有将Visual本身转换为BitmapSource
,它包含转换结果为{{1} }}。要使用此MSDN Forum Post代码的修改版本将BitmapSource
转换为BitmapSource
,请尝试使用。{/ p>
System.Drawing.Bitmap
创建一个返回Bitmap的方法
renderBitmap.Render(dv);
BitmapSource bmp = renderBitmap;
using(MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bmp));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
VideoStream aviStream=aviManager.AddVideoStream(true,60,bitmap);
}
renderBitmap.Render(dv);
BitmapSource bmp =renderBitmap;
VideoStream aviStream = aviManager.AddVideoStream(true, 60, ConvertToBitmap(bmp));
答案 1 :(得分:0)
private BitmapSource ToBitmapSource(Visual visual, Brush transparentBackground)
{
var bounds = VisualTreeHelper.GetDescendantBounds(visual);
var bitmapSource = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Pbgra32);
var drawingVisual = new DrawingVisual();
using (var drawingContext = drawingVisual.RenderOpen())
{
var visualBrush = new VisualBrush(visual);
drawingContext.DrawRectangle(transparentBackground, null, new Rect(new Point(), bounds.Size));
drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(), bounds.Size));
}
bitmapSource.Render(drawingVisual);
return bitmapSource;
}
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;
}