C#: Save a canvas as an image

This C# code saves a Canvas as a *.PNG image:

private void CreateSaveBitmap(Canvas canvas, string filename)
     {
       RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)canvas.Width, (int)canvas.Height,
        96d, 96d, PixelFormats.Pbgra32);
      // needed otherwise the image output is black
       canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height));
       canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height)));

renderBitmap.Render(canvas);

//JpegBitmapEncoder encoder = new JpegBitmapEncoder();
       PngBitmapEncoder encoder = new PngBitmapEncoder();
       encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

using (FileStream file = File.Create(filename))
       {
         encoder.Save(file);
       }
     }

Use it like this:

CreateSaveBitmap(myCanvas, @"C:\temp\out.png");
About these ads

2 thoughts on “C#: Save a canvas as an image

  1. After saving my image was shifted at the right bottom conner.
    With this code it isn’t:

    canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height));
    canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height)));

    Thank you!

  2. Hi, thanks for sharing, I have a problem when I save the canvas as image, the problem is the canvas position or size doesn’t save properly, I don’t know how to solve it. I think the problem is like Michael’s. Can you help me please? Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s