Convert RenderTargetBitmap to System.Drawing.Image

I have a 3D render of WPF that I want to transfer to an Excel cell (via the clipboard).

With "normal" BMP images, this works, but I don't know how to convert a RenderTargetBitmap .

My code is as follows:

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

My problem is that gr.DrawImage does not accept System.Windows.Controls.Image or System.Windows.Media.Imaging.RenderTargetBitmap ; only a System.Drawing.Image .

How do I convert Controls.Image.Imaging.RenderTargetBitmap to Image , or are there any simpler ways?

+4
source share
3 answers

That was the solution I came up with

 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
source

You can copy pixels from the RenderTargetBitmap directly to the pixel buffer of the new Bitmap . Note that I suggested that your RenderTargetBitmap uses PixelFormats.Pbrga32 , as using any other pixel format will throw an exception from the RenderTargetBitmap constructor.

 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
source

Maybe I do not understand the question correctly, but you want to copy the RenderTargetBitmap to the clipboard, could you just call 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) 
0
source

All Articles