This is a familiar situation that most developers run into. The need to save a canvas element to a png file.
Scenario
- You have few strokes drawn on a canvas and you want to save it as a png .
- You want to save the just the strokes on a transparent background.
- You want to save the strokes along with the canvas background.
- You want to save it with your specified sizes
I too ran into this ditch lately. And had a tough time finding a solution. A random google search will give you numerous methods, most of which is applicable only to traditional C#/.NET application.
Then I found this MSDN link. I still have’nt figured out how to use a PNGEncoder and DeCoder. If anyone finds a good blog about it, feel free to post it here. Many of the solutions I found never worked. The searches how ever led me to the WriteableBitmapEx hosted at codeplex. It had several useful functions but none to save a canvas to an image.
A week’s search, frustration, irritation, trial & error of several broken classes finally led me to ToolStack. It is mentioned that it works for Windows Phone 7.1 but I have implemented in WP8 project. There 3 classes which will do the job neatly, although compression is not yet implemented.
- ToolStackPNGWriterWBext.cs – Implementation of WriteableBitmapExtensions
- ToolStackPNGWriterLib.cs – Core Class and implementation of saving to PNG
- ToolStackCRCLib.cs – Additional classes needed for ToolStackPNGWriterLib.
Getting it working on your project.
- Download all necessary files from ToolStack. Download the example too and run it first so that you can understand how it works.
- Add the Classes mentioned to your project.
- Create a Writeablebitmap of your canvas and then use the WritePNG function to save
1234
</pre>
WriteableBitmap wb =
new
WriteableBitmap(MyCanvas,
null
);
wb.WritePNG(MyStreamforWriteAsync);
<pre>
And there your image lies in the specified location, in the size of your canvas!
NOTE TO WIN8 DEVELOPERS
If you try to implement the same functionality in a metro app, you’re in for trouble mate. Because the very simple function which allows to capture a canvas onto a WriteableBitmap does not exist! There is a method to save the inkstrokes though, but only the portion containing the stroke will be saved. You cannot save it along with its transparent/colored background. I consulted few developers and they seem to have no answer too. It seems this is possible in JavaScript.
Lets see if Windows 8.1 contains something for us developers in this direction.
Happy Coding!!