using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;

namespace WpfSaveBitmap
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Make a 3D array because that's easier to use.
            const int width = 240;
            const int height = 240;
            byte[,,] pixels = new byte[height, width, 4];

            // Color the pixels.
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int num = (int)(x / 48) + (int)(y / 48);
                    switch (num % 3)
                    {
                        case 0:     // Red
                            pixels[x, y, 2] = 255;
                            break;
                        case 1:     // Green
                            pixels[x, y, 1] = 255;
                            break;
                        case 2:     // Blue
                            pixels[x, y, 0] = 255;
                            break;
                    }
                    pixels[x, y, 3] = 255;  // Alpha
                }
            }

            // Copy the data into a one-dimensional array.
            byte[] pixels1d = new byte[height * width * 4];
            Buffer.BlockCopy(pixels, 0, pixels1d, 0, pixels.Length);

            // Make the WriteableBitmap.
            WriteableBitmap wbitmap = new WriteableBitmap(
                width, height, 96, 96, PixelFormats.Bgra32, null);

            // Copy the color data into the WriteableBitmap.
            Int32Rect rect = new Int32Rect(0, 0, width, height);
            int stride = 4 * width;
            wbitmap.WritePixels(rect, pixels1d, stride, 0);

            // Create an Image to display the WriteableBitmap.
            Image image = new Image();
            image.Stretch = Stretch.None;
            image.Margin = new Thickness(0);
            grdMain.Children.Add(image);

            //Set the Image source.
            image.Source = wbitmap;

            // Save the bitmap into some files.
            wbitmap.Save("Checkerboard.bmp");
            wbitmap.Save("Checkerboard.gif");
            wbitmap.Save("Checkerboard.jpg");
            wbitmap.Save("Checkerboard.png");
            wbitmap.Save("Checkerboard.tif");
            wbitmap.Save("Checkerboard.wmp");
        }
    }
}
