我有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
,还是有更简单的方法?
答案 0 :(得分:4)
您可以将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);
答案 1 :(得分: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);
答案 2 :(得分: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)