我有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
,或者有没有更简单的方法? 最佳答案
您可以将像素从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);
关于c# - 将RenderTargetBitmap转换为System.Drawing.Image,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7808717/