c# - 如何将 DrawingVisual 转换为位图?

标签 c# image bitmap drawingvisual

使用 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。

我找到了做类似事情的示例代码,但它们似乎都想实例化 Image 类,Visual Studio 告诉我该类是抽象的,无法实例化。

我在兜圈子,一事无成。

我只想做这样的事情:

...
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);

最佳答案

使用RenderTargetBitMap的结果是一个 WPF BitMapSource它不会将 Visual 本身转换为 BitmapSource,它包含作为 BitmapSource 的转换结果。为了将 BitmapSource 转换为 System.Drawing.Bitmap,尝试使用此 MSDN Forum Post 中代码的修改版本.

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));

private System.Drawing.Bitmap ConvertToBitmap(BitmapSource target)
{
    System.Drawing.Bitmap bitmap;

    using (MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(target));
        enc.Save(outStream);
        bitmap = new System.Drawing.Bitmap(outStream);
    }

    return bitmap;
}

关于c# - 如何将 DrawingVisual 转换为位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12227941/

相关文章:

java - 在线获取 UTC 时间的可靠方法?

c# - ProjectGuid(.csproj),如何正确生成?

c# - 列出所有容器和 blob

c# - ILogger 未将 TRACE 和 DEBUG 消息写入目标

r - 如何将图像上传到 RStudio Notebook?

android - 使用 Google Drive Android API 从 Google Drive 下载图片?

javascript - JS : Bend height on left and right side of an image

android - 将 webview 转换为位图

c# - 如何将多个图像合并为一个图像?

C# 从 MP4 流中提取位图