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);
}
}