Search
Close this search box.

Export Canvas to PNG and save it in your local folder

** Just a last minute update, from Arnoud: 

Found the ultimate Silverlight PNG encoder with zip-compression..
http://www.codeplex.com/Wiki/View.aspx?ProjectName=imagetools

And about the license, can be used for commercial purpose (check this thread: http://silverlight.net/forums/p/105680/250333.aspx#250333)

And about… saving a canvas as PNG compressed:

http://imagetools.codeplex.com/Wiki/View.aspx?title=Write the content of a canvas to a file

Hope to get some extra time to create a new post with all this new updates :-).

**

One of the missing functionality of SL 2.0 was the ability to export a canvas content as an image and let the user save it to his local file storage. We had to use nasty tricks to implement that: rountrip to server side, draw again the content using GDI+ (server side) and dumping that in a bitmap…

In SL 3.0 they have incorporated:

–          A class called WriteableBitmap, that allows us dumping a canvas content into an image.

–          A Save File Dialog that allows us to save the given image in the client’s local file system.

But… it still has a limitation:

–          SL 3.0 does not implement code to save as PNG or JPEG.

Is there any solution for this? Well the thing is you can implement in SL an algorithm to save in such formats, pain in the… J well we are lucky somebody has already done that for us.

I have packed in a library the excellent work from:

–          Andy Beaulieu has implemented a class that get the writableBitmap content and encode in PNG format. 

http://www.andybeaulieu.com/Home/tabid/67/EntryID/161/Default.aspx

 –          Tom Giam, code to grab that stream and save it to local.

http://silverlight.net/forums/t/108713.aspx

–          Pete Brown: good concept explanation plus excellent support (interesting to read the comment section)

The library is called ImageExportLib, and how you can use it:

  CanvasToPNG canvasToPNG = new CanvasToPNG();
 
            // It will export to PNG the canvas content
            // parameter canvas ID
            canvasToPNG.ShowSaveDialog(canvasToExport);

About the sample: Draws some basic shapes and let’s you save it as PNG on your local file system:

You can download the whole solution:

http://www.tipsdotnet.com/Images/Canvas_To_PNG.zip

Next Steps To do:

–          Check for FJCore to allow JPEG export.

–          Check why is limited to 2047×2047 width and height

–          Define error handling (simple doesn’t capture exceptions).

–          Properly comment the code, based on the excellent info published by Andy and Tom.

This article is part of the GWB Archives. Original Author:  Braulio Díez Botella

Related Posts