Save the wpf view as an image, preferably .png

I have a search and understand how to save an image in WPF using BmpBitmapEncoder . My program has an MVVM view that I want to save as an image. Is it possible to set it as a BitmapFrame so that I can encode it? If so, is there an online tutorial?

Below is the view I want to save.

  <Grid> <view:OverallView Grid.Row="1" Visibility="{Binding IsOverallVisible,Converter={StaticResource B2VConv}}" /> </Grid> 

OverallView is a user control.


If setting the view as a BitmapFrame not possible, then what wpf elements can be set as BitmapSource/Frame ?

+8
c # wpf mvvm
source share
1 answer

You can return it as a RenderTargetBitmap :

 public static RenderTargetBitmap GetImage(OverallView view) { Size size = new Size(view.ActualWidth, view.ActualHeight); if (size.IsEmpty) return null; RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingvisual = new DrawingVisual(); using (DrawingContext context = drawingvisual.RenderOpen()) { context.DrawRectangle(new VisualBrush(view), null, new Rect(new Point(), size)); context.Close(); } result.Render(drawingvisual); return result; } 

After that, you can use PngBitmapEncoder to save it as PNG and save it in a stream, for example:

 public static void SaveAsPng(RenderTargetBitmap src, Stream outputStream) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(src)); encoder.Save(outputStream); } 

FIX: bitmap => result

+16
source share

Source: https://habr.com/ru/post/650546/


All Articles