Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a WPF canvas as an image

Tags:

c#

.net

wpf

I was following this article and I got my canvas to be saved, however, I want to extend the code's functionality and save a particular part of my canvas as an image, rather than my entire canvas.

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

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

Thanks!

like image 692
Jonathan Perry Avatar asked Jan 16 '12 15:01

Jonathan Perry


1 Answers

A simple method would be to use a CroppedBitmap after rendering the whole canvas. You could reuse 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);
}

If you want to save to a bitmap object instead of a file, you can use:

using (Stream s = new MemoryStream())
{
    pngEncoder.Save(s);
    Bitmap myBitmap = new Bitmap(s);
}
like image 123
Kris Avatar answered Sep 21 '22 00:09

Kris