using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Windows.Media.Imaging;

namespace WpfSaveBitmap
{
    public static class WriteableBitmapExtentions
    {
        // Save the WriteableBitmap into a PNG file.
        public static void Save(this WriteableBitmap wbitmap, string filename)
        {
            // Make the right kind of encoder depending on the file name's extension.
            BitmapEncoder encoder = null;
            string extension = Path.GetExtension(filename);
            switch (extension.ToLower())
            {
                case ".bmp":
                    encoder = new BmpBitmapEncoder();
                    break;
                //case ".exif":
                //    encoder = new ExifBitmapEncoder();
                //    break;
                case ".gif":
                    encoder = new GifBitmapEncoder();
                    break;
                case ".jpg":
                case ".jpeg":
                    encoder = new JpegBitmapEncoder();
                    break;
                case ".png":
                    encoder = new PngBitmapEncoder();
                    break;
                case ".tif":
                case ".tiff":
                    encoder = new TiffBitmapEncoder();
                    break;
                case ".wmp":    // Microsoft Window Media Photo
                    encoder = new WmpBitmapEncoder();
                    break;
                default:
                    throw new NotSupportedException(
                        "Unknown file extension " + extension);
            }

            // Add the bitmap to the encoder's Frames collection.
            encoder.Frames.Add(BitmapFrame.Create(wbitmap));

            // Save the file.
            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                encoder.Save(stream);
            }
        }
    }
}
