Example #1
0
        /// <summary>
        /// Returns a buffer with the contents of the given stream.
        /// <param name="stream">Source stream</param>
        /// <returns>Buffer with the contents of the given stream</returns>
        /// </summary>
        private IBuffer StreamToBuffer(Stream stream)
        {
            var memoryStream = stream as MemoryStream;

            if (memoryStream == null)
            {
                using (memoryStream = new MemoryStream())
                {
                    stream.Position = 0;
                    stream.CopyTo(memoryStream);

                    try
                    {
                        // Some stream types do not support flushing

                        stream.Flush();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }

                    return memoryStream.GetWindowsRuntimeBuffer();
                }
            }
            else
            {
                return memoryStream.GetWindowsRuntimeBuffer();
            }
        }
Example #2
0
        internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, UInt32 count)
        {
            Contract.Requires(stream != null);
            Contract.Requires(stream is MemoryStream);
            Contract.Requires(stream.CanRead);
            Contract.Requires(stream.CanSeek);
            Contract.Requires(buffer != null);
            Contract.Requires(buffer is IBufferByteAccess);
            Contract.Requires(0 <= count);
            Contract.Requires(count <= Int32.MaxValue);
            Contract.Requires(count <= buffer.Capacity);
            Contract.EndContractBlock();

            // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
            // This is permitted by the WinRT stream contract.
            // The user specified buffer will not have any data put into it:
            buffer.Length = 0;

            MemoryStream memStream = stream as MemoryStream;
            Debug.Assert(memStream != null);

            try
            {
                IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((Int32)memStream.Position, (Int32)count);
                if (dataBuffer.Length > 0)
                    memStream.Seek(dataBuffer.Length, SeekOrigin.Current);

                return AsyncInfo.CreateCompletedOperation<IBuffer, UInt32>(dataBuffer);
            }
            catch (Exception ex)
            {
                return AsyncInfo.CreateFaultedOperation<IBuffer, UInt32>(ex);
            }
        }  // ReadAsync_MemoryStream
Example #3
0
        // Sample the original image
        private void SampleOriginalImage()
        {
            originalBitmap = new WriteableBitmap(originalImage);
            double ratio = (double)originalBitmap.PixelWidth / (double)originalBitmap.PixelHeight;
            double w = Application.Current.RootVisual.RenderSize.Width;
            double h = Application.Current.RootVisual.RenderSize.Height;
            double previewWidth;
            double previewHeight;

            if (w / ratio > h)
            {
                previewHeight = h;
                previewWidth = h * ratio;
            }
            else
            {
                previewWidth = w;
                previewHeight = w / ratio;
            }

            originalPreviewBitmap = originalBitmap.Resize((int)previewWidth, (int)previewHeight, System.Windows.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);
            currentPreviewBitmap = originalBitmap.Resize((int)previewWidth, (int)previewHeight, System.Windows.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);

            // Create buffer
            previewStream = new MemoryStream();
            currentPreviewBitmap.SaveJpeg(previewStream, originalPreviewBitmap.PixelWidth, originalPreviewBitmap.PixelHeight, 0, 75);
            previewBuffer = previewStream.GetWindowsRuntimeBuffer();
        }
Example #4
0
 private IBuffer GetServerChallenge()
 {
     using (var ms = new MemoryStream())
     {
         using (var sw = new StreamWriter(ms))
         {
             sw.Write(_serverChallenge);
         }
         return ms.GetWindowsRuntimeBuffer();
     }
 }
        /// <summary>Saves the current session state. </summary>
        public static async Task SaveAsync()
        {
            foreach (var weakFrameReference in _registeredFrames)
            {
                MtFrame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                    SaveFrameNavigationState(frame);
            }

            var sessionData = new MemoryStream();
            var serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);

            var folder = ApplicationData.Current.LocalFolder; 
            var file = await folder.CreateFileAsync(SessionStateFilename, CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteBufferAsync(file, sessionData.GetWindowsRuntimeBuffer());
        }
        private async void ApplyFilterToBackgroundImageAsync()
        {
            MemoryStream bitmapStream = new MemoryStream();
            Source.SaveJpeg(bitmapStream, Source.PixelWidth, Source.PixelHeight, 0, 50);
            IBuffer bmpBuffer = bitmapStream.GetWindowsRuntimeBuffer();

            // Output buffer
            WriteableBitmap outputImage = new WriteableBitmap(Source.PixelWidth, Source.PixelHeight);

            using (EditingSession editsession = new EditingSession(bmpBuffer))
            {
                // First add an antique effect 
                editsession.AddFilter(FilterFactory.CreateBlurFilter(BlurLevel.Blur6));

                // Finally, execute the filtering and render to a bitmap
                await editsession.RenderToBitmapAsync(outputImage.AsBitmap());
                outputImage.Invalidate();
                FadeInNewImage(outputImage);
            }
        }
Example #7
0
        public static PhotoModel RestorePhotoModel()
        {
            PhotoModel model = null;

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // parameters.xml

                if (storage.FileExists(_photoModelPath + @"\" + _photoModelPropertiesFilename))
                {
                    IsolatedStorageFileStream propertiesFile = storage.OpenFile(_photoModelPath + @"\" + _photoModelPropertiesFilename, FileMode.Open, FileAccess.Read);

                    XmlSerializer serializer = new XmlSerializer(typeof(PhotoModel));

                    model = serializer.Deserialize(propertiesFile) as PhotoModel;

                    propertiesFile.Flush();
                    propertiesFile.Close();
                }

                // buffer.data

                if (model != null && storage.FileExists(_photoModelPath + @"\" + _photoModelBufferFilename))
                {
                    IsolatedStorageFileStream originalFile = storage.OpenFile(_photoModelPath + @"\" + _photoModelBufferFilename, FileMode.Open, FileAccess.Read);

                    MemoryStream stream = new MemoryStream();
                    originalFile.CopyTo(stream);

                    model.Buffer = stream.GetWindowsRuntimeBuffer();

                    originalFile.Flush();
                    originalFile.Close();
                }
            }

            return model;
        }
        public async Task<IBuffer> TakePicture()
        {
            if (m_captureDevice == null || commandeRunning)
                return null;
            try
            {
                commandeRunning = true;
                int angle = (int)(m_orientationAngle + m_captureDevice.SensorRotationInDegrees);
                if (angle < 0) angle += 360;
                if (m_sensorLocation == CameraSensorLocation.Back)
                {
                    m_captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, angle);
                }
                else
                {
                    m_captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, -angle);
                }
                m_captureDevice.SetProperty(KnownCameraGeneralProperties.SpecifiedCaptureOrientation, 0);


                var cameraCaptureSequence = m_captureDevice.CreateCaptureSequence(1);
                var stream = new MemoryStream();
                cameraCaptureSequence.Frames[0].CaptureStream = stream.AsOutputStream();
                await m_captureDevice.PrepareCaptureSequenceAsync(cameraCaptureSequence);
                await cameraCaptureSequence.StartCaptureAsync();
                if (m_sensorLocation == CameraSensorLocation.Back)
                {
                    return stream.GetWindowsRuntimeBuffer();
                }
                else
                {
                    return await JpegTools.FlipAndRotateAsync(stream.GetWindowsRuntimeBuffer(), FlipMode.Horizontal, Rotation.Rotate0, JpegOperation.AllowLossy);
                }

            }
            finally
            {
                commandeRunning = false;
            }
            return null;
        }
Example #9
0
        private async System.Threading.Tasks.Task Capture()
        {
            try
            {
                await camera.FocusAsync();

                MemoryStream imageStream = new MemoryStream();
                imageStream.Seek(0, SeekOrigin.Begin);

                CameraCaptureSequence sequence = camera.CreateCaptureSequence(1);
                sequence.Frames[0].CaptureStream = imageStream.AsOutputStream();

                await camera.PrepareCaptureSequenceAsync(sequence);
                await sequence.StartCaptureAsync();

                camera.SetProperty(
                KnownCameraPhotoProperties.LockedAutoFocusParameters,
                AutoFocusParameters.None);

                MediaLibrary library = new MediaLibrary();

                EditingSession session = new EditingSession(imageStream.GetWindowsRuntimeBuffer());

                using (session)
                {
                    session.AddFilter(FilterFactory.CreateSketchFilter(SketchMode.Gray));
                    IBuffer data = await session.RenderToJpegAsync();
                    library.SavePictureToCameraRoll(FileNamePrefix
                                + DateTime.Now.ToString() + ".jpg",
                                data.AsStream());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to save the image to camera roll: " + ex.ToString());
            }
        }
Example #10
0
        public async Task<Stream> ApplyEffect(MemoryStream inputStream)
        {
            if (_effectIndex >= 0 && _effectIndex < EffectGroup.Count)
            {
                AbstractFilter filter = EffectGroup[_effectIndex];
                IBuffer outputBuffer = null;

                if (_semaphore.WaitOne(500))
                {
                    outputBuffer = await filter.RenderJpegAsync(inputStream.GetWindowsRuntimeBuffer());
                    _semaphore.Release();
                }

                if (outputBuffer != null)
                {
                    return outputBuffer.AsStream();
                }
            }
            return null;
        }
        public static async System.Threading.Tasks.Task SavePathImageAsFile(int Width, int Height, string fileName, FrameworkElement element, bool UseRenderTarget = true)
        {
            double oldWidth     = element.Width;
            double oldHeight    = element.Height;
            double actOldWidth  = element.ActualWidth;
            double actOldHeight = element.ActualHeight;

            //if (!UseRenderTarget)
            {
                //engine takes the Ceiling so make sure its below or sometimes off by 1 rounding up from ActualWidth/Height
                element.Width = !UseRenderTarget?Math.Floor((float)Math.Min(Window.Current.Bounds.Width, Width)) : (float)Math.Min(Window.Current.Bounds.Width, Width);

                element.Height = !UseRenderTarget?Math.Floor((float)Math.Min(Window.Current.Bounds.Height, Height)) : (float)Math.Min(Window.Current.Bounds.Height, Height);

                //bool bHasCalledUpdateLayout = false;
                //should wrap into another event handler and check a bHasCalledUpdateLayout to ignore early calls and race condition
                //object lockVar = new object();
                //EventHandler<object> eventHandler = null;
                //System.Threading.Tasks.TaskCompletionSource<object> t = new System.Threading.Tasks.TaskCompletionSource<object>();
                //eventHandler = (sender, e) => { lock (lockVar) { if (bHasCalledUpdateLayout && Math.Abs(element.ActualWidth - element.Width) <= 1 && Math.Abs(element.ActualHeight - element.Height) <= 1) { lock (lockVar) { if (bHasCalledUpdateLayout) { bHasCalledUpdateLayout = false; t.SetResult(e); } } } } };
                //element.LayoutUpdated += eventHandler;
                //lock (lockVar) {
                //    element.UpdateLayout();
                //    bHasCalledUpdateLayout = true;
                //}
                ////await element.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => element.Dispatcher.ProcessEvents(Windows.UI.Core.CoreProcessEventsOption.ProcessAllIfPresent)));
                //await t.Task;
                //element.LayoutUpdated -= eventHandler;
                await element.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { });

                if (!UseRenderTarget && (element.ActualWidth > element.Width || element.ActualHeight > element.Height))
                {
                    if (element.ActualWidth > element.Width)
                    {
                        element.Width -= 1;
                    }
                    if (element.ActualHeight > element.Height)
                    {
                        element.Height -= 1;
                    }
                    //bHasCalledUpdateLayout = false;
                    //t = new System.Threading.Tasks.TaskCompletionSource<object>();
                    //eventHandler = (sender, e) => { lock (lockVar) { if (bHasCalledUpdateLayout && Math.Abs(element.ActualWidth - element.Width) <= 1 && Math.Abs(element.ActualHeight - element.Height) <= 1) { lock (lockVar) { if (bHasCalledUpdateLayout) { bHasCalledUpdateLayout = false; t.SetResult(e); } } } } };
                    //element.LayoutUpdated += eventHandler;
                    //lock (lockVar)
                    //{
                    //    element.UpdateLayout();
                    //    bHasCalledUpdateLayout = true;
                    //}
                    //await t.Task;
                    //element.LayoutUpdated -= eventHandler;
                    await element.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { });
                }
            }
#if WINDOWS_APP && STORETOOLKIT
            if (!UseRenderTarget)
            {
                System.IO.MemoryStream memstream = await WinRTXamlToolkit.Composition.WriteableBitmapRenderExtensions.RenderToPngStream(element);

                Windows.Storage.StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName + ".png", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                await stream.WriteAsync(memstream.GetWindowsRuntimeBuffer());

                stream.Dispose();
            }
            else
            {
#endif
            //Canvas cvs = new Canvas();
            //cvs.Width = Width;
            //cvs.Height = Height;
            //Windows.UI.Xaml.Shapes.Path path = new Windows.UI.Xaml.Shapes.Path();
            //object val;
            //Resources.TryGetValue((object)"PathString", out val);
            //Binding b = new Binding
            //{
            //    Source = (string)val
            //};
            //BindingOperations.SetBinding(path, Windows.UI.Xaml.Shapes.Path.DataProperty, b);
            //cvs.Children.Add(path);
            float dpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;
            Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap wb = new Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap();
            await wb.RenderAsync(element, (int)((float)Width * 96 / dpi), (int)((float)Height * 96 / dpi));

            Windows.Storage.Streams.IBuffer buf = await wb.GetPixelsAsync();

            Windows.Storage.StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName + ".png", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            //Windows.Graphics.Imaging.BitmapPropertySet propertySet = new Windows.Graphics.Imaging.BitmapPropertySet();
            //propertySet.Add("ImageQuality", new Windows.Graphics.Imaging.BitmapTypedValue(1.0, Windows.Foundation.PropertyType.Single)); // Maximum quality
            Windows.Graphics.Imaging.BitmapEncoder be = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, stream);    //, propertySet);

            be.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied, (uint)wb.PixelWidth, (uint)wb.PixelHeight, dpi, dpi, buf.ToArray());
            await be.FlushAsync();

            await stream.GetOutputStreamAt(0).FlushAsync();

            stream.Dispose();
#if WINDOWS_APP && STORETOOLKIT
        }
#endif
            //if (!UseRenderTarget)
            {
                element.Width  = oldWidth;
                element.Height = oldHeight;
                //bHasCalledUpdateLayout = false;
                //t = new System.Threading.Tasks.TaskCompletionSource<object>();
                //eventHandler = (sender, e) => { lock (lockVar) { if (bHasCalledUpdateLayout && Math.Abs(element.ActualWidth - actOldWidth) <= 1 && Math.Abs(element.ActualHeight - actOldHeight) <= 1) { lock (lockVar) { if (bHasCalledUpdateLayout) { bHasCalledUpdateLayout = false; t.SetResult(e); } } } } };
                //element.LayoutUpdated += eventHandler;
                //lock (lockVar)
                //{
                //    element.UpdateLayout();
                //    bHasCalledUpdateLayout = true;
                //}
                //await t.Task;
                //element.LayoutUpdated -= eventHandler;
                await element.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { });
            }
        }
Example #12
0
		private void GenerateResponseHash()
		{
            var ae = new UTF8Encoding();

            var v = NextInt64();

            // Create cnonce value using a random number, username and password
            var sb = new StringBuilder();
            sb.Append(v.ToString());
            sb.Append(":");
            sb.Append(Id.User);
            sb.Append(":");
            sb.Append(Password);

            _cnonce = HexString(ae.GetBytes(sb.ToString())).ToLower();

            // Create the nonce count which states how many times we have sent this packet.
            _nc++;
            _ncString = _nc.ToString().PadLeft(8, '0');

            // Create H1.  This value is the username/password portion of A1 according to the SASL DIGEST-MD5 RFC.
            sb.Remove(0, sb.Length);
            sb.Append(Id.User);
            sb.Append(":");
            sb.Append(this["realm"]);
            sb.Append(":");
            sb.Append(Password);
            var h1 = _md5.HashData( (ae.GetBytes(sb.ToString())).AsBuffer()).ToArray();

            // Create the rest of A1 as stated in the RFC.
            sb.Remove(0, sb.Length);
            sb.Append(":");
            sb.Append(this["nonce"]);
            sb.Append(":");
            sb.Append(_cnonce);

            if (this["authzid"] != null)
            {
                sb.Append(":");
                sb.Append(this["authzid"]);
            }

            var a1 = sb.ToString();

            // Combine H1 and A1 into final A1
            var ms = new MemoryStream();
            ms.Write(h1, 0, 16);
            var temp = ae.GetBytes(a1);
            ms.Write(temp, 0, temp.Length);
            ms.Seek(0, SeekOrigin.Begin);
            h1 = _md5.HashData( ms.GetWindowsRuntimeBuffer() ).ToArray();

            //Create A2
            sb.Remove(0, sb.Length);
            sb.Append("AUTHENTICATE:");
            sb.Append(_digestUri);
            if (this["qop"].CompareTo("auth") != 0)
            {
                sb.Append(":00000000000000000000000000000000");
            }
            var a2 = sb.ToString();
            var h2 = _md5.HashData( (ae.GetBytes(a2)).AsBuffer() ).ToArray();

            // Make A1 and A2 hex strings
            var p1 = HexString(h1).ToLower();
            var p2 = HexString(h2).ToLower();

            // Combine all portions into the final response hex string
            sb.Remove(0, sb.Length);
            sb.Append(p1);
            sb.Append(":");
            sb.Append(this["nonce"]);
            sb.Append(":");
            sb.Append(_ncString);
            sb.Append(":");
            sb.Append(_cnonce);
            sb.Append(":");
            sb.Append(this["qop"]);
            sb.Append(":");
            sb.Append(p2);

            var a3 = sb.ToString();
            var h3 = _md5.HashData( (ae.GetBytes(a3)).AsBuffer() ).ToArray();
            _responseHash = HexString(h3).ToLower();
		}
Example #13
0
        private async void SetPhotoFromEditedPage(string FiledID)
        {
            MediaLibrary library = new MediaLibrary();
            Picture photoFromLibrary = library.GetPictureFromToken(FiledID);

            using (MemoryStream stream = new MemoryStream())
            {
                photoFromLibrary.GetImage().CopyTo(stream);

                App.PhotoModel = new PhotoModel() { Buffer = stream.GetWindowsRuntimeBuffer() };
                App.PhotoModel.Captured = true;
                App.PhotoModel.Dirty = true;
                
                Setup();
                pgrAddress.Visibility = System.Windows.Visibility.Visible;
                await RenderAsync();
                pgrAddress.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
Example #14
0
        private void Task_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                if (Helpers.FileHelpers.IsValidPicture(e.OriginalFileName))
                {
                    if (App.PhotoModel != null)
                    {
                        App.PhotoModel.Dispose();
                        App.PhotoModel = null;

                        GC.Collect();
                    }

                    using (MemoryStream stream = new MemoryStream())
                    {
                        e.ChosenPhoto.CopyTo(stream);

                        App.PhotoModel = new PhotoModel() { Buffer = stream.GetWindowsRuntimeBuffer() };
                        App.PhotoModel.Captured = (sender == _cameraCaptureTask);
                        App.PhotoModel.Dirty = App.PhotoModel.Captured;
                    }

                    Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri("/Pages/PhotoPage.xaml", UriKind.Relative)); });
                }
                else
                {
                    MessageBox.Show(AppResources.App_MessageBox_UnsupportedImage_Message,
                        AppResources.App_MessageBox_UnsupportedImage_Caption, MessageBoxButton.OK);
                }
            }
        }
        public async void PrepareImageForUploadAsync()
        {
            WriteableBitmap bmp = new WriteableBitmap(OriginalImage);

            bitmapStream = new MemoryStream();
            bmp.SaveJpeg(bitmapStream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
            IBuffer bmpBuffer = bitmapStream.GetWindowsRuntimeBuffer();

            // Output buffer
            bitmapForUpload = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight);

            using (EditingSession editsession = new EditingSession(bmpBuffer))
            {
                // First add an antique effect 
                foreach (FilterBase fx in FilterManager.AppliedFilters)
                {
                    editsession.AddFilter(fx.FinalOutputFilter);
                }                

                // Finally, execute the filtering and render to a bitmap
                await editsession.RenderToBitmapAsync(bitmapForUpload.AsBitmap());
                bitmapForUpload.Invalidate();

                bitmapStream.Close();
                bitmapStream = null;
            }

            Dispatcher.BeginInvoke(() => {
                BeginUpload();
            });
        }
Example #16
0
        private async void Task_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                if (Helpers.FileHelpers.IsValidPicture(e.OriginalFileName))
                {
                    if (App.PhotoModel != null)
                    {
                        App.PhotoModel.Dispose();
                        App.PhotoModel = null;

                        GC.Collect();
                    }

                    using (MemoryStream stream = new MemoryStream())
                    {
                        e.ChosenPhoto.CopyTo(stream);

                        App.PhotoModel = new PhotoModel() { Buffer = stream.GetWindowsRuntimeBuffer() };
                        App.PhotoModel.Captured = (sender == _cameraCaptureTask);
                        App.PhotoModel.Dirty = App.PhotoModel.Captured;
                        App.PhotoModel.Path = e.OriginalFileName;
                    }

                    if (_loaded)
                    {
                        await SetupAsync();
                        await RenderAsync();
                    }
                }
                else
                {
                    MessageBox.Show(AppResources.App_MessageBox_UnsupportedImage_Message,
                        AppResources.App_MessageBox_UnsupportedImage_Caption, MessageBoxButton.OK);
                }
            }
        }
        /// <summary>
        /// Begins a photo stream item rendering process loop. Loop is executed asynchronously item by item
        /// until there are no more items in the queue.
        /// </summary>
        private async void Process()
        {
            _processingNow++;

            while (_enabled && Count > 0)
            {
                StreamItemViewModel item;

                if (_priorityQueue.Count > 0)
                {
                    Busy = true;

                    item = _priorityQueue[0];

                    _priorityQueue.RemoveAt(0);
                }
                else
                {
                    item = _standardQueue[0];

                    _standardQueue.RemoveAt(0);
                }

                try
                {
                    WriteableBitmap bitmap = null;

                    using (MemoryStream thumbnailStream = new MemoryStream())
                    {
                        System.Diagnostics.Debug.Assert(item.RequestedSize != StreamItemViewModel.Size.None);

                        if (item.RequestedSize == StreamItemViewModel.Size.Large)
                        {
                            bitmap = new WriteableBitmap(280, 280);

                            item.Model.Picture.GetImage().CopyTo(thumbnailStream);
                        }
                        else if (item.RequestedSize == StreamItemViewModel.Size.Medium)
                        {
                            bitmap = new WriteableBitmap(140, 140);

                            item.Model.Picture.GetThumbnail().CopyTo(thumbnailStream);
                        }
                        else
                        {
                            bitmap = new WriteableBitmap(70, 70);

                            item.Model.Picture.GetThumbnail().CopyTo(thumbnailStream);
                        }

                        using (EditingSession session = new EditingSession(thumbnailStream.GetWindowsRuntimeBuffer()))
                        {
                            Windows.Foundation.Rect rect;

                            if (session.Dimensions.Width > session.Dimensions.Height)
                            {
                                rect = new Windows.Foundation.Rect()
                                {
                                    Width = session.Dimensions.Height,
                                    Height = session.Dimensions.Height,
                                    X = session.Dimensions.Width / 2 - session.Dimensions.Height / 2,
                                    Y = 0
                                };
                            }
                            else
                            {
                                rect = new Windows.Foundation.Rect()
                                {
                                    Width = session.Dimensions.Width,
                                    Height = session.Dimensions.Width,
                                    X = 0,
                                    Y = session.Dimensions.Height / 2 - session.Dimensions.Width / 2
                                };
                            }

                            session.AddFilter(FilterFactory.CreateCropFilter(rect));

                            if (item.Model.Filter != null)
                            {
                                foreach (IFilter f in item.Model.Filter.Components)
                                {
                                    session.AddFilter(f);
                                }
                            }

                            await session.RenderToBitmapAsync(bitmap.AsBitmap());
                        }
                    }
                    
                    item.TransitionToImage(bitmap);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Rendering stream item failed:" + ex.Message);

                    item.TransitionToImage(null);
                }
            }

            _processingNow--;

            if (_processingNow == 0)
            {
                Busy = false;
            }
        }
        public async Task<IBuffer> TakePicture()
        {
            if (_photoCaptureDevice == null && _cameraSemaphore.WaitOne(100))
                return null;

            if (_cameraSemaphore.WaitOne(100))
            {
                try
                {
                    int angle = 0;

                    if (Orientation.HasFlag(PageOrientation.LandscapeLeft))
                    {
                        angle = (int)_photoCaptureDevice.SensorRotationInDegrees - 90;
                    }
                    else if (Orientation.HasFlag(PageOrientation.LandscapeRight))
                    {
                        angle = (int)_photoCaptureDevice.SensorRotationInDegrees + 90;
                    }
                    else // PageOrientation.PortraitUp
                    {
                        angle = (int)_photoCaptureDevice.SensorRotationInDegrees;
                    }


                    if (angle < 0) angle += 360;
                    if (_cameraLocation == CameraSensorLocation.Back)
                    {
                        _photoCaptureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, angle);
                    }
                    else
                    {
                        _photoCaptureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, -angle);
                    }
                    _photoCaptureDevice.SetProperty(KnownCameraGeneralProperties.SpecifiedCaptureOrientation, 0);


                    var cameraCaptureSequence = _photoCaptureDevice.CreateCaptureSequence(1);
                    var stream = new MemoryStream();
                    cameraCaptureSequence.Frames[0].CaptureStream = stream.AsOutputStream();
                    await _photoCaptureDevice.PrepareCaptureSequenceAsync(cameraCaptureSequence);
                    await cameraCaptureSequence.StartCaptureAsync();


                    IBuffer capturedPicture;
                    if (_cameraLocation == CameraSensorLocation.Back)
                    {
                        capturedPicture = stream.GetWindowsRuntimeBuffer();
                    }
                    else
                    {
                        capturedPicture = await JpegTools.FlipAndRotateAsync(stream.GetWindowsRuntimeBuffer(), FlipMode.Horizontal, Rotation.Rotate0, JpegOperation.AllowLossy);
                    }


                    using (var source = new StreamImageSource(capturedPicture.AsStream()))
                    {
                        var recipe = RecipeFactory.Current.CreatePipeline(source);
                        using (var renderer = new JpegRenderer(recipe))
                        {
                            capturedPicture = await renderer.RenderAsync();
                        }
                        if (recipe is IDisposable)
                            (recipe as IDisposable).Dispose();
                    }
                    return capturedPicture;
                }
                finally
                {
                    _cameraSemaphore.Release();
                }
            }

            return null;
        }