This is a familiar situation that most developers run into. The need to save a canvas element to a png file.
- 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
</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! 🙂 Remember to add the necessary using statements in your file. Any canvas element can be captured into a WritableBitmap, even an InkPresenter can be captured.
NOTE TO WIN8 DEVELOPERS
Lets see if Windows 8.1 contains something for us developers in this direction.
Happy Coding!! 😀