Save WPF Canvas as Image

I followed this article and I got my canvas to save, however I want to extend the functionality of the code and save a certain part of my canvas as an image, and not my entire canvas.

I tried setting the properties rect.Offset and rect.Location , but the image is always saved in the upper left corner of my canvas.

Does anyone know how I can achieve my desired functionality in a similar way?

Thanks!

+7
source share
3 answers

A simple method would be to use CroppedBitmap after rendering the entire canvas. You can use the same RenderTargetBitmap if you need multiple images.

 RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas.RenderSize.Width, (int)canvas.RenderSize.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default); rtb.Render(canvas); var crop = new CroppedBitmap(rtb, new Int32Rect(50, 50, 250, 250)); BitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(BitmapFrame.Create(crop)); using(var fs = System.IO.File.OpenWrite("logo.png")) { pngEncoder.Save(fs); } 
+15
source

See if this solution works for you.

 Size size = new Size(width, height); canvas.Measure(size); canvas.Arrange(new Rect(X, Y, width, height)); //Save Image ... ... // Revert old position canvas.Measure(new Size()); 
0
source

By looking at the link you posted, obviously, you can select the displayed target coordinates here.

 RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right, (int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default); 
0
source

All Articles