将RenderTargetBitmap转换为System.Drawing.Image

6

我有一个与3D WPF相关的可视化图形,我想通过剪贴板缓冲区将它传递到Excel单元格中。

对于“普通”的BMP图像,它可以工作,但我不知道如何转换RenderTargetBitmap

我的代码如下:

System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = myParent.GetViewPortAsImage(DiagramSizeX, DiagramSizeY);
System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
myImage.Source = renderTarget;

System.Drawing.Bitmap pg = new System.Drawing.Bitmap(DiagramSizeX, DiagramSizeY);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(pg);
gr.DrawImage(myImage, 0, 0);

System.Windows.Forms.Clipboard.SetDataObject(pg, true);
sheet.Paste(range);

我的问题是gr.DrawImage不接受System.Windows.Controls.Image或者System.Windows.Media.Imaging.RenderTargetBitmap,只接受System.Drawing.Image

我该如何将Controls.Image.Imaging.RenderTargetBitmap转换为Image,或者有没有更简单的方法?

3个回答

6

您可以直接将RenderTargetBitmap中的像素复制到新的Bitmap的像素缓冲区中。请注意,我假设您的RenderTargetBitmap使用PixelFormats.Pbrga32,因为使用其他任何像素格式都会从RenderTargetBitmap的构造函数中抛出异常。

var bitmap = new Bitmap(renderTarget.PixelWidth, renderTarget.PixelHeight,
    PixelFormat.Format32bppPArgb);

var bitmapData = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size),
    ImageLockMode.WriteOnly, bitmap.PixelFormat);

renderTarget.CopyPixels(Int32Rect.Empty, bitmapData.Scan0,
    bitmapData.Stride*bitmapData.Height, bitmapData.Stride);

bitmap.UnlockBits(bitmapData);

2
这是我想出来的解决方案。
System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = myParent.GetViewPortAsImage(DiagramSizeX, DiagramSizeY);
System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
MemoryStream myStream = new MemoryStream();

encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget));
encoder.Save(myStream);
//
System.Drawing.Bitmap pg = new System.Drawing.Bitmap(DiagramSizeX, DiagramSizeY);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(pg);
//
// Background
//
gr.FillRectangle(new System.Drawing.SolidBrush(BKGC), 0, 0, DiagramSizeX, DiagramSizeY);
//
gr.DrawImage(System.Drawing.Bitmap.FromStream(myStream), 0, 0);
System.Windows.Forms.Clipboard.SetDataObject(pg, true);

sheet.Paste(range);

0
也许我没有理解问题,但是您想将RenderTargetBitmap复制到剪贴板中,难道您不能只调用SetImage吗?
    Dim iRT As RenderTargetBitmap = makeImage() //this is what you do to get the rendertargetbitmap
    If iRT Is Nothing Then Exit Sub
    Clipboard.SetImage(iRT)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接