using System;
using System.Collections.Generic;
using System.Text;
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.Shapes;

namespace BitmapProgramming
{
    /// <summary>
    /// Interaction logic for ModifyPixels.xaml
    /// </summary>

    public partial class ModifyPixels : System.Windows.Window
    {

        public ModifyPixels()
        {
            InitializeComponent();

            // Example 13-34. Modifying pixels

            BitmapImage originalBmp = new BitmapImage();
            originalBmp.BeginInit();
            originalBmp.UriSource = new Uri(
               "http://www.interact-sw.co.uk/images/M3/BackOfM3.jpeg");
            originalBmp.DownloadCompleted += delegate
            {

                BitmapSource prgbaSource = new FormatConvertedBitmap(originalBmp,
                                                 PixelFormats.Pbgra32, null, 0);
                WriteableBitmap bmp = new WriteableBitmap(prgbaSource);

                int w = bmp.PixelWidth;
                int h = bmp.PixelHeight;
                int[] pixelData = new int[w * h];
                int widthInBytes = 4 * w;

                bmp.CopyPixels(pixelData, widthInBytes, 0);
                for (int i = 0; i < pixelData.Length; ++i)
                {
                    pixelData[i] ^= 0x00ffffff;
                }
                bmp.WritePixels(new Int32Rect(0, 0, w, h),
                    pixelData, widthInBytes, 0);


                // bmp now ready for use
                imageElement.Source = bmp;
            };

            originalBmp.EndInit();

            // End of Example 13-34.

        }

    }
}