Convert RenderTargetBitmap to Bitmap

MC9000 picture MC9000 · Nov 19, 2013 · Viewed 16.1k times · Source

This looks like a dup question, it is, but no one has answered the actual question(s).

Here goes: Basically, I'm rendering a ViewPort3D as a 2D snapshot in code, but need to convert that type RenderTargetBitmap into the type System.Drawing.Bitmap (for further processing on the 2D side).

Dim bmpRen As New RenderTargetBitmap(1024, 550, 96, 96, PixelFormats.Pbgra32)
bmpRen.Render(Me.vp3dTiles) 'render the viewport as 2D snapshot

While I know how to save it to a file, I'd rather skip that step and convert the bmpRen to a System.Drawing.Bitmap type, but there is no method to do so.

Answer

Nathan Dace picture Nathan Dace · Nov 19, 2013

RenderedTargetBitmap is a BitmapSource, so the BmpBitmapEncoder can do the conversion for us:

This is in C#, but it should translate to VB without any problems.

RenderTargetBitmap bmpRen = new RenderTargetBitmap(1024, 550, 96, 96, PixelFormats.Pbgra32);
bmpRen.Render(vp3dTiles);

MemoryStream stream = new MemoryStream();
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmpRen));
encoder.Save(stream);

Bitmap bitmap = new Bitmap(stream);