转载并改进自 https://www.cnblogs.com/xiaokang088/archive/2011/03/29/1998918.html
public static MemoryStream GetImageFromFrameworkElement(FrameworkElement element)
{
MemoryStream ms = null;
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext context = drawingVisual.RenderOpen())
{
VisualBrush brush = new VisualBrush(element) { Stretch = Stretch.None };
context.DrawRectangle(brush, null, new Rect(0, 0, element.ActualWidth, element.ActualHeight));
context.Close();
}
//dpi可以自己设定 // 获取dpi方法:PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(drawingVisual);
PngBitmapEncoder encode = new PngBitmapEncoder();
encode.Frames.Add(BitmapFrame.Create(bitmap));
ms = new MemoryStream();
encode.Save(ms);
return ms;
}