Write the content of a canvas to a file

To write the content of a canvas to a file you need the following Assemblies:
  • ImageTools
  • ImageTools.Util
  • ImageTools.IO.Png
The png format is the default format in the image tools library. Therefore all extension methods use the png encoder.

1. Save the image as png file

To create a out image out of an canvas just use the following code:
ImageTools myImage = MyCanvas.ToImage();

Then use the SaveFileDialog to write the image to a file:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Image Files (*.png)|*.png";

if (sfd.ShowDialog() == true)
{
   using (Stream stream = sfd.OpenFile())
   {
      myImage.WriteToStream(stream);
   }
}

2. Choose a image encoder.

If you want to save the file as jpg add a reference to the ImageTools.IO.Jpeg assembly and use the JpegEncoder:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Image Files (*.png)|*.png";

if (sfd.ShowDialog() == true)
{
   using (Stream stream = sfd.OpenFile())
   {
      JpegEncoder encoder = new JpegEncoder();
      encoder.Encode(myImage, stream);
      
      stream.Close();
   }
} 

3. Save the image to the different formats

The library also provides a method which select the encoder by the file extension. If you want to support other formats than png you must register the encoders before:
ImageTools.IO.Encoders.AddEncoder<ImageTools.IO.Jpeg.JpegEncoder>();
ImageTools.IO.Encoders.AddEncoder<ImageTools.IO.Bmp.BmpEncoder>();

The code to write the image to the stream is more or less the same. Just set the target file name to give the method the possibility to select the encoder.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Image Files (*.png)|*.png";

if (sfd.ShowDialog() == true)
{
   using (Stream stream = sfd.OpenFile())
   {
      myImage.WriteToStream(stream, sfd.SafeFileName);
   }
}
Last edited Jul 18 2009 at 1:32 PM by malignate88, version 4
Comments
No comments yet.

Updating...
© 2006-2010 Microsoft | About CodePlex | Privacy Statement | Terms of Use | Code of Conduct | Advertise With Us | Version 2010.1.12.16187