public void swapBackground(chromaKeyImageData _newData)
 {
     if (gsView != null)
     {
         gsView.changeBackground(_newData);
     }
 }
        /// <summary>
        /// Users are instructed to name files like this:
        /// 1_Foreground.png
        /// 1_Background.png
        /// 
        /// 1_Background.png
        /// 
        /// 2_Background_Greyscale.png
        /// 
        /// 2_Foreground_Greyscale.png
        /// 2_Background_Greyscale.png
        /// 
        /// Assuming they name them right, we assume that below.
        /// </summary>
        private void loadChromaKeyPhotos()
        {

            // Start by pulling everything in the directory
            List<chromaKeyImageData> loadedChromaPhotoData = new List<chromaKeyImageData>();
            string saveDirPath = System.AppDomain.CurrentDomain.BaseDirectory + "localFiles\\backgroundImages\\";

            // put files into collection
            DirectoryInfo info = new DirectoryInfo(saveDirPath);
            FileSystemInfo[] files = info.GetFileSystemInfos();
            // Sort them by name and only use pngs
            var Orderedfiles = files.Where(f => f.Extension == ".png" || f.Extension == ".PNG")
                                    .OrderBy(f => f.Name);

            // Current item we are working on at any given time
            chromaKeyImageData currentChromaKeyItem = null;
            
            int currentLoop = 0;
            foreach (FileSystemInfo fi in Orderedfiles)
            {
                currentLoop += 1;

                    // We actually attempt to load each file here into memory.
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.Proxy = null;  //avoids dynamic proxy discovery delay
                        webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
                        try
                        {
                            byte[] imageBytes = null;
                            imageBytes = webClient.DownloadData(fi.FullName);
                            try
                            {
                                MemoryStream imageStream = new MemoryStream(imageBytes);
                                BitmapImage currentImage = new BitmapImage();
                                currentImage.BeginInit();
                                currentImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                                currentImage.CacheOption = BitmapCacheOption.OnLoad;
                                currentImage.StreamSource = imageStream;
                                currentImage.EndInit();
                                currentImage.Freeze();
                                imageStream.Close();

                                // Try and extract the index from the filename as we need it
                                // reguardless
                                string resultIndex = Regex.Match(fi.Name, @"\d+").Value;
                                // If that went well we now need to know where to put this guy
                                // Its a new entry
                                if (currentChromaKeyItem == null)
                                {
                                    currentChromaKeyItem = new chromaKeyImageData();
                                }
                                else
                                {
                                    // An exhisting entry
                                    // Try and extract the number
                                    if (resultIndex != "")
                                    {
                                        // Does it match our current index?
                                        int parsedIndex = int.Parse(resultIndex);
                                        if (parsedIndex != currentChromaKeyItem.Index)
                                        {
                                            // Its a new index - add the old entry to the main list
                                            loadedChromaPhotoData.Add(currentChromaKeyItem);
                                            currentChromaKeyItem = new chromaKeyImageData();
                                        }
                                    }
                                    else
                                    {
                                        // Just going to have to assume its new. Shove the last one on the loaded data
                                        loadedChromaPhotoData.Add(currentChromaKeyItem);
                                        currentChromaKeyItem = new chromaKeyImageData();
                                    }
                                }
                                // Set the index
                                currentChromaKeyItem.Index = int.Parse(resultIndex);
                                // OK now figure out if this is Foreground or Background
                                if (fi.Name.ToUpper().Contains("BACKGROUND"))
                                {
                                    // IST A BACKGROUND
                                    currentChromaKeyItem.BackgroundImageNameOnly = fi.Name;
                                    currentChromaKeyItem.BackgroundImageBM = currentImage;
                                }
                                else
                                {
                                    // ITS A FOREGROUND
                                    currentChromaKeyItem.ForegroundImageNameOnly = fi.Name;
                                    currentChromaKeyItem.ForegroundImageBM = currentImage;
                                }
                                // OK now figure out if it needs greyscale
                                if (fi.Name.ToUpper().Contains("GREYSCALE"))
                                {
                                    currentChromaKeyItem.greyscale = true;
                                }
                                // Check if both a foreground and background are present OR this is the last item- if so add it and set the current null
                                // for the next round ALSO check for the last item
                                if ( (currentChromaKeyItem.ForegroundImageBM != null && currentChromaKeyItem.BackgroundImageBM != null) || (currentLoop == Orderedfiles.Count() ) )
                                {
                                    loadedChromaPhotoData.Add(currentChromaKeyItem);
                                    currentChromaKeyItem = null;
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Error loading media during chroma key load: " + e.ToString());
                            }
                        }
                        catch (WebException ex)
                        {
                            //do something to report the exception
                            System.Diagnostics.Debug.WriteLine("Exception Downloading Image : " + ex.ToString());
                        }
                    }
            }

            // Dispatch so everyone knows we are ready
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                if (photoLoadProgress != null)
                {
                    PhotoLoadEventArgs newArgs = new PhotoLoadEventArgs(1.0, loadedChromaPhotoData);
                    photoLoadProgress(this, newArgs);
                }
            }));

            // ----> END OF THREAD/BG WORKER
        }
        private void setupKinectOrNoK(chromaKeyImageData _initalData)
        {
            // Create the background image reguardless
            _bgImage = new Image();
            _bgImage.Name = "backgroundImage";
            _bgImage.Width = _thisWidth;
            _bgImage.Height = _thisHeight;
            _bgImage.Stretch = Stretch.Fill;
            kiddieHolder.Children.Add(_bgImage);

            _bgImage.Source = _initalData.BackgroundImageBM;

            if (_sensor != null)
            {
                // Create the image
                _kColorImage = new Image();
                _kColorImage.Name = "UserPhoto";
                _kColorImage.Width = 640 * Properties.Settings.Default.kinectDepthImageScale;
                _kColorImage.Height = 480 * Properties.Settings.Default.kinectDepthImageScale;
                kiddieHolder.Children.Add(_kColorImage);
                // This does fill or exceede the visual area but the kinects depth stream is not as large as the color stream..so we need to offset the left and
                // top by a uniform ammount as we scale too.
                Canvas.SetTop(_kColorImage, _depthTopOffset);
                Canvas.SetLeft(_kColorImage, _depthLeftOffset);

                this.colorBitmap = new WriteableBitmap(this._sensor.ColorStream.FrameWidth, this._sensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
                this.maskBitmap = new WriteableBitmap(_sensor.DepthStream.FrameWidth, _sensor.DepthStream.FrameHeight, 96, 96, PixelFormats.Bgra32, null);
                this._kColorImage.Source = this.colorBitmap;

                // colorBitmap serves as our main source for the player image - BUT we have an opacity mask on that guy too which is generated
                // from an image brush made by our "green screen" data. By having that secondary image we can use fast WPF blurs on it and do other
                // manipulations
                _blurMaskSource = new Image();
                blurMaskEffect = new BlurEffect();
                blurMaskEffect.Radius = _postblurAmmount;

                blurMaskVisualBrush = new VisualBrush();
                blurMaskVisualBrush.Visual = _blurMaskSource;
                //_blurMaskSource.Source = maskBitmap;
                _blurMaskSource.Effect = blurMaskEffect;

                this._kColorImage.OpacityMask = this.blurMaskVisualBrush;

                // Init the green screen work horse
                _greenScreenProcessor = new GreenScreenImplementation(this._sensor);
                _blurMaskSource.Source = _greenScreenProcessor.greenScreenMask;
                _greenScreenProcessor.frameReadyForDisplay += greenScreenFrameReady;

                _sensor.AllFramesReady += kinectAllFramesReady;
            }
            else
            {
                // Create the kinect needed
                _noKinect = new KFWIcon();
                _noKinect.Name = "kwfLogo";
                _noKinect.Width = 328;
                _noKinect.Height = 180;
                _noKinect.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                _noKinect.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                kiddieHolder.Children.Add(_noKinect);
            }

            // Foreground too, but it may not have anything
            _fgImage = new Image();
            _fgImage.Name = "foregroundImage";
            _fgImage.Width = _thisWidth;
            _fgImage.Height = _thisHeight;
            _fgImage.Stretch = Stretch.Fill;
            kiddieHolder.Children.Add(_fgImage);

            if (_initalData.ForegroundImageBM != null)
            {
                _fgImage.Source = _initalData.ForegroundImageBM;
            }
        }
 public void changeBackground(chromaKeyImageData _newKeyPhotoData)
 {
     if (_bgImage != null)
     {
         if (_newKeyPhotoData.BackgroundImageBM != null)
         {
             _bgImage.Source = _newKeyPhotoData.BackgroundImageBM;
         }
     }
     if (_fgImage != null)
     {
         if (_newKeyPhotoData.ForegroundImageBM != null)
         {
             _fgImage.Source = _newKeyPhotoData.ForegroundImageBM;
         }
         else
         {
             _fgImage.Source = null;
         }
     }
 }
        /// <summary>
        /// In this version the chromaKeyImageData contains already loaded BitmapImages
        /// </summary>
        /// <param name="sensor"></param>
        /// <param name="_width"></param>
        /// <param name="_height"></param>
        /// <param name="_initialBG"></param>
        /// <param name="_initialFG"></param>
        public void init(ref KinectSensor sensor, double _width, double _height, chromaKeyImageData _initialChromaKData)
        {
            _sensor = sensor;
            _thisWidth = _width;
            _thisHeight = _height;

            setupKinectOrNoK(_initialChromaKData);
            // Ensure we only have ONE photo submitter
            _photoSubmitter = new ThreadedPhotoSubmission();
            _photoSubmitter.ImageSubmissionComplete += handlePhotoSubmittedToCMS;

        }
        /// <summary>
        /// Users are instructed to name files like this:
        /// 1_Foreground.png
        /// 1_Background.png
        ///
        /// 1_Background.png
        ///
        /// 2_Background_Greyscale.png
        ///
        /// 2_Foreground_Greyscale.png
        /// 2_Background_Greyscale.png
        ///
        /// Assuming they name them right, we assume that below.
        /// </summary>
        private void loadChromaKeyPhotos()
        {
            // Start by pulling everything in the directory
            List <chromaKeyImageData> loadedChromaPhotoData = new List <chromaKeyImageData>();
            string saveDirPath = System.AppDomain.CurrentDomain.BaseDirectory + "localFiles\\backgroundImages\\";

            // put files into collection
            DirectoryInfo info = new DirectoryInfo(saveDirPath);

            FileSystemInfo[] files = info.GetFileSystemInfos();
            // Sort them by name and only use pngs
            var Orderedfiles = files.Where(f => f.Extension == ".png" || f.Extension == ".PNG")
                               .OrderBy(f => f.Name);

            // Current item we are working on at any given time
            chromaKeyImageData currentChromaKeyItem = null;

            int currentLoop = 0;

            foreach (FileSystemInfo fi in Orderedfiles)
            {
                currentLoop += 1;

                // We actually attempt to load each file here into memory.
                using (WebClient webClient = new WebClient())
                {
                    webClient.Proxy       = null; //avoids dynamic proxy discovery delay
                    webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
                    try
                    {
                        byte[] imageBytes = null;
                        imageBytes = webClient.DownloadData(fi.FullName);
                        try
                        {
                            MemoryStream imageStream  = new MemoryStream(imageBytes);
                            BitmapImage  currentImage = new BitmapImage();
                            currentImage.BeginInit();
                            currentImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                            currentImage.CacheOption   = BitmapCacheOption.OnLoad;
                            currentImage.StreamSource  = imageStream;
                            currentImage.EndInit();
                            currentImage.Freeze();
                            imageStream.Close();

                            // Try and extract the index from the filename as we need it
                            // reguardless
                            string resultIndex = Regex.Match(fi.Name, @"\d+").Value;
                            // If that went well we now need to know where to put this guy
                            // Its a new entry
                            if (currentChromaKeyItem == null)
                            {
                                currentChromaKeyItem = new chromaKeyImageData();
                            }
                            else
                            {
                                // An exhisting entry
                                // Try and extract the number
                                if (resultIndex != "")
                                {
                                    // Does it match our current index?
                                    int parsedIndex = int.Parse(resultIndex);
                                    if (parsedIndex != currentChromaKeyItem.Index)
                                    {
                                        // Its a new index - add the old entry to the main list
                                        loadedChromaPhotoData.Add(currentChromaKeyItem);
                                        currentChromaKeyItem = new chromaKeyImageData();
                                    }
                                }
                                else
                                {
                                    // Just going to have to assume its new. Shove the last one on the loaded data
                                    loadedChromaPhotoData.Add(currentChromaKeyItem);
                                    currentChromaKeyItem = new chromaKeyImageData();
                                }
                            }
                            // Set the index
                            currentChromaKeyItem.Index = int.Parse(resultIndex);
                            // OK now figure out if this is Foreground or Background
                            if (fi.Name.ToUpper().Contains("BACKGROUND"))
                            {
                                // IST A BACKGROUND
                                currentChromaKeyItem.BackgroundImageNameOnly = fi.Name;
                                currentChromaKeyItem.BackgroundImageBM       = currentImage;
                            }
                            else
                            {
                                // ITS A FOREGROUND
                                currentChromaKeyItem.ForegroundImageNameOnly = fi.Name;
                                currentChromaKeyItem.ForegroundImageBM       = currentImage;
                            }
                            // OK now figure out if it needs greyscale
                            if (fi.Name.ToUpper().Contains("GREYSCALE"))
                            {
                                currentChromaKeyItem.greyscale = true;
                            }
                            // Check if both a foreground and background are present OR this is the last item- if so add it and set the current null
                            // for the next round ALSO check for the last item
                            if ((currentChromaKeyItem.ForegroundImageBM != null && currentChromaKeyItem.BackgroundImageBM != null) || (currentLoop == Orderedfiles.Count()))
                            {
                                loadedChromaPhotoData.Add(currentChromaKeyItem);
                                currentChromaKeyItem = null;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error loading media during chroma key load: " + e.ToString());
                        }
                    }
                    catch (WebException ex)
                    {
                        //do something to report the exception
                        System.Diagnostics.Debug.WriteLine("Exception Downloading Image : " + ex.ToString());
                    }
                }
            }

            // Dispatch so everyone knows we are ready
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                if (photoLoadProgress != null)
                {
                    PhotoLoadEventArgs newArgs = new PhotoLoadEventArgs(1.0, loadedChromaPhotoData);
                    photoLoadProgress(this, newArgs);
                }
            }));

            // ----> END OF THREAD/BG WORKER
        }