示例#1
0
        private async void task_Completed(object sender, PhotoResult e)
        {
            /* byte[] imageBits = new byte[(int)e.ChosenPhoto.Length];
            e.ChosenPhoto.Read(imageBits, 0, imageBits.Length);
            e.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);
            MemoryStream screenshot = new MemoryStream(imageBits);
            BitmapImage imageFromStream = new BitmapImage();
            imageFromStream.SetSource(screenshot); */
            Stream imgstream = e.ChosenPhoto;
            //System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
            //bmp.SetSource(e.ChosenPhoto);
            //img.Source = bmp;
            ApplyButton.Visibility = Visibility.Visible;
            session = await EditingSessionFactory.CreateEditingSessionAsync(imgstream);
            try
            {
                session.AddFilter(FilterFactory.CreateCartoonFilter(true));

                // Save the image as a jpeg to the camera roll
                using (MemoryStream stream = new MemoryStream())
                {
                    WriteableBitmap bitmap = new WriteableBitmap(3552, 2448);
                    await session.RenderToWriteableBitmapAsync(bitmap);
                    bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                    img.Source = bitmap;
                }
                //Force the framework to redraw the Image.
            }
            catch (Exception exception)
            {
                MessageBox.Show("Exception:" + exception.Message);
            }
            
        }
示例#2
0
        private async Task ShowImageAsync()
        {
            _originalStream.Seek(0, SeekOrigin.Begin);
            Helpers.SafeDispose(ref _editingSession);
            _editingSession = await EditingSessionFactory.CreateEditingSessionAsync(_originalStream);

            ImageWidth  = (int)_editingSession.Dimensions.Width;
            ImageHeight = (int)_editingSession.Dimensions.Height;

            MainImage = new WriteableBitmap(ImageWidth, ImageHeight);
            await _editingSession.RenderToWriteableBitmapAsync(MainImage);

            _buffer     = new int[MainImage.PixelWidth * MainImage.PixelHeight];
            _maskBuffer = new byte[MainImage.PixelWidth * MainImage.PixelHeight];
            _oldPixels  = new int[MainImage.PixelWidth * MainImage.PixelHeight];
            MainImage.Pixels.CopyTo(_oldPixels, 0);
            MainImage.Invalidate();
            PreviewImage = null;

            BindTool();

            if (_backup == null)
            {
                _backup = new WriteableBitmap(MainImage.PixelWidth, MainImage.PixelHeight);
                MainImage.Pixels.CopyTo(_backup.Pixels, 0);
            }

            CanApply = false;
            HasImage = true;
        }
示例#3
0
        private async void UndoExecute()
        {
            _buffer        = new int[MainImage.PixelWidth * MainImage.PixelHeight];
            _maskBuffer    = new byte[MainImage.PixelWidth * MainImage.PixelHeight];
            _filterApplied = false;

            _originalStream.Seek(0, SeekOrigin.Begin);
            _editingSession = await EditingSessionFactory.CreateEditingSessionAsync(_originalStream);

            await _editingSession.RenderToWriteableBitmapAsync(MainImage);

            MainImage.Invalidate();

            CanApply   = false;
            _noChanges = true;
            UndoCommand.RaiseCanExecuteChanged();

            if (PreviewImage != null)
            {
                for (var i = 0; i < PreviewImage.Pixels.Length; ++i)
                {
                    PreviewImage.Pixels[i] = 0;
                }
                PreviewImage.Invalidate();
            }

            BindTool();
        }
示例#4
0
        public EditingSession EditingSession(CmsForm form, Type entityType, IDictionary <string, string> initialValues)
        {
            var session = new EditingSession {
                InitialValues = initialValues
            };

            var widgetsGroupedByProperty = GetClientSideWidgetLookup(form);
            var editingScope             = BuildObjectEditingScope(form);

            var properties = ToolboxMetadataReader.ReadProperties(entityType, x => editingScope.Contains(x.Name))
                             .ToDictionary(x => x.PropertyInfo.Name);



            foreach (var widgetGroup in widgetsGroupedByProperty)
            {
                var propertyName             = widgetGroup.Key;
                var widgetsNeedingDataSource = widgetGroup.ToList();

                foreach (var widget in widgetsNeedingDataSource)
                {
                    var dataSource = new RequiresDataSource();
                    dataSource.SetPropertyValues(widget.Parameters, x => true);


                    var isLinkedToRepository = dataSource.DataSourceType == DataSourceTypes.Repository &&
                                               dataSource.RepositoryApiId != default(Guid);
                    if (isLinkedToRepository)
                    {
                        var entities          = GetDataRelationshipEntities(dataSource, properties[propertyName]);
                        var asDataSourceItems = entities.Select(x => new DataSourceItem {
                            Name = x.Title, Value = x.ContentId.ToString()
                        }).ToList();
                        var ds = new LocalDataSource {
                            Items = asDataSourceItems
                        };
                        session.LocalDataSources.Add(propertyName, ds);
                        continue;
                    }

                    var isLinkedToFixedSet = dataSource.DataSourceType == DataSourceTypes.FixedItems;
                    if (isLinkedToFixedSet)
                    {
                        var ds = new LocalDataSource {
                            Items = dataSource.Items.Items
                        };
                        session.LocalDataSources.Add(propertyName, ds);
                        continue;
                    }
                }
            }

            return(session);
        }
示例#5
0
        /// <summary>
        /// For the given bitmap renders filtered thumbnails for each filter in given list and populates
        /// the given wrap panel with the them.
        ///
        /// For quick rendering, renders 10 thumbnails synchronously and then releases the calling thread.
        /// </summary>
        /// <param name="bitmap">Source bitmap to be filtered</param>
        /// <param name="side">Side length of square thumbnails to be generated</param>
        /// <param name="list">List of filters to be used, one per each thumbnail to be generated</param>
        /// <param name="panel">Wrap panel to be populated with the generated thumbnails</param>
        private async Task RenderThumbnailsAsync(Bitmap bitmap, int side, List <FilterModel> list, WrapPanel panel)
        {
            using (EditingSession session = new EditingSession(bitmap))
            {
                int i = 0;

                foreach (FilterModel filter in list)
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(side, side);

                    foreach (IFilter f in filter.Components)
                    {
                        session.AddFilter(f);
                    }

                    Windows.Foundation.IAsyncAction action = session.RenderToBitmapAsync(writeableBitmap.AsBitmap());

                    i++;

                    if (i % 10 == 0)
                    {
                        // async, give control back to UI before proceeding.
                        await action;
                    }
                    else
                    {
                        // synchroneous, we keep the CPU for ourselves.
                        Task task = action.AsTask();
                        task.Wait();
                    }

                    PhotoThumbnail photoThumbnail = new PhotoThumbnail()
                    {
                        Bitmap = writeableBitmap,
                        Text   = filter.Name,
                        Width  = side,
                        Margin = new Thickness(6)
                    };

                    photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) =>
                    {
                        App.PhotoModel.ApplyFilter(filter);
                        App.PhotoModel.Dirty = true;

                        NavigationService.GoBack();
                    };

                    panel.Children.Add(photoThumbnail);

                    session.UndoAll();
                }
            }
        }
示例#6
0
        private async void UpdatePreviewAsync()
        {
            using (EditingSession session = new EditingSession(previewBuffer))
            {
                // Add all previous filters
                foreach (FilterBase filterContainer in filterManager.AppliedFilters)
                {
                    if (filterContainer.IsFilterEnabled)
                    {
                        session.AddFilter(filterContainer.Filter);
                    }
                }

                await session.RenderToWriteableBitmapAsync(currentPreviewBitmap, OutputOption.PreserveAspectRatio);
                currentPreviewBitmap.Invalidate();
            }
        }
示例#7
0
        public async Task GetNewFrameAndApplyEffect(IBuffer processedBuffer)
        {
            if (captureDevice == null)
            {
                return;
            }

            captureDevice.GetPreviewBufferArgb(cameraBitmap.Pixels);

            Bitmap outputBtm = new Bitmap(
                outputBufferSize,
                ColorMode.Bgra8888,
                (uint)outputBufferSize.Width * 4, // 4 bytes per pixel in BGRA888 mode
                processedBuffer);

            EditingSession session = new EditingSession(cameraBitmap.AsBitmap());
            session.AddFilter(FilterFactory.CreateSketchFilter(SketchMode.Gray));
            await session.RenderToBitmapAsync(outputBtm);

        }
        //public string Info()
        //{
        //    try
        //    {
        //        return string.Format("Input size = {0}x{1}\nLR : {2,5:F} ms [{3,5:F} {4,5:F}]\nHR : {5,5:F} ms [{6,5:F} {7,5:F}]\n",
        //            inputSize.Width, inputSize.Height,
        //            nbLRImage > 0 ? sumLRtime.TotalMilliseconds / nbLRImage : 0,
        //            minLRtime.TotalMilliseconds,
        //            maxLRtime.TotalMilliseconds,
        //            nbHRImage > 0 ? sumHRtime.TotalMilliseconds / nbHRImage : 0,
        //            minHRtime.TotalMilliseconds,
        //            maxHRtime.TotalMilliseconds,
        //            inputSize.Width, inputSize.Height)
        //            +
        //            string.Format("\nType = {0}\nDuration : {1,5:F} \nScale : {2,5:F}\nAngle : {3,5:F}\nPos :  [{4,5:F} , {5,5:F}]",
        //            outputResolution == RESOLUTION.LOW ? "LR" : "HR",
        //            lastDuration.TotalMilliseconds,
        //            currentScale,
        //            currentAngle,
        //            currentPos.X, currentPos.Y);
        //    }
        //    catch (Exception e)
        //    {
        //        return "";
        //    }
        //}

        public void Dispose()
        {
            if (session != null)
            {
                session.Dispose();
            }
            session           = null;
            outputBitmapLRTmp = null;
            outputBitmapLR    = null;
            outputBitmapHRTmp = null;
            outputBitmapHR    = null;

            if (output != null)
            {
                output.ManipulationStarted   -= ManipulationStarted;
                output.ManipulationDelta     -= ManipulationDelta;
                output.ManipulationCompleted -= ManipulationCompleted;
            }
            output = null;
        }
        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);
            }
        }
示例#10
0
        public async Task ApplyDifficultyToImage(Stream image, Difficulty level, Image resultImage)
        {
            try
            {
                using (EditingSession _session = await EditingSessionFactory.CreateEditingSessionAsync(image))
                {
                    switch (level)
                    {
                    case Difficulty.Easy:
                        _session.AddFilter(_easyFilterGroup);
                        break;

                    case Difficulty.Moderate:
                        _session.AddFilter(_moderateFilterGroup);
                        break;

                    case Difficulty.Hard:
                        _session.AddFilter(_hardFilterGroup);
                        break;

                    case Difficulty.VeryHard:
                        _session.AddFilter(_veryHardFilterGroup);
                        break;

                    case Difficulty.ReallyHard:
                        _session.AddFilter(_impossibleFilterGroup);
                        break;

                    default:
                        break;
                    }

                    //Render the image to the Image control in the Quiz page
                    await _session.RenderToImageAsync(resultImage);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred while processing the image: " + e.Message);
            }
        }
示例#11
0
        async void setInput(Stream s)
        {
            //Dispose old session ressources.
            if (session != null)
            {
                session.Dispose();
                session = null;
            }
            //reset stream position
            s.Seek(0, SeekOrigin.Begin);
            //create a session
            var tmpsession = await EditingSessionFactory.CreateEditingSessionAsync(s);

            tmpsession.AddFilter(FilterFactory.CreateCropFilter(new Rect(0, 0, 1, 1)));
            var foo = await tmpsession.RenderToJpegAsync();

            tmpsession.UndoAll();
            session = tmpsession;

            inputSize = new Size()
            {
                Width = session.Dimensions.Width, Height = session.Dimensions.Height
            };
            currentPos = new Point(session.Dimensions.Width / 2, session.Dimensions.Height / 2);
            if (session.Dimensions.Width > session.Dimensions.Height)
            {
                currentScale = output.Height / session.Dimensions.Height;
            }
            else
            {
                currentScale = output.Width / session.Dimensions.Width;
            }
            currentAngle = 0.0;
            saveLastPossaveLastPositionData();
            requestProcessing();
        }
示例#12
0
        private async void task_Completed(object sender, PhotoResult e)
        {
            /* byte[] imageBits = new byte[(int)e.ChosenPhoto.Length];
             * e.ChosenPhoto.Read(imageBits, 0, imageBits.Length);
             * e.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);
             * MemoryStream screenshot = new MemoryStream(imageBits);
             * BitmapImage imageFromStream = new BitmapImage();
             * imageFromStream.SetSource(screenshot); */
            Stream imgstream = e.ChosenPhoto;

            //System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
            //bmp.SetSource(e.ChosenPhoto);
            //img.Source = bmp;
            ApplyButton.Visibility = Visibility.Visible;
            session = await EditingSessionFactory.CreateEditingSessionAsync(imgstream);

            try
            {
                session.AddFilter(FilterFactory.CreateCartoonFilter(true));

                // Save the image as a jpeg to the camera roll
                using (MemoryStream stream = new MemoryStream())
                {
                    WriteableBitmap bitmap = new WriteableBitmap(3552, 2448);
                    await session.RenderToWriteableBitmapAsync(bitmap);

                    bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                    img.Source = bitmap;
                }
                //Force the framework to redraw the Image.
            }
            catch (Exception exception)
            {
                MessageBox.Show("Exception:" + exception.Message);
            }
        }
        /// <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 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();
            });
        }
示例#15
0
        private async void ApplyExecute()
        {
            IsWorking = true;

            if (_editingSession == null || _noChanges)
            {
                return;
            }

            if (!CanApply)
            {
                _queued = true;
                return;
            }

            CanApply = false;

            _filterApplied = true;
            if (_filterApplied && _editingSession.CanUndo())
            {
                try { _editingSession.Undo(); }
                catch (Exception e)
                {
                    App.LogError(e);
                }
            }

            // apply filter to selected pixels only
            PreviewImage = new WriteableBitmap(ImageWidth, ImageHeight);
            _buffer.CopyTo(PreviewImage.Pixels, 0);

            using (var ms = PreviewImage.ToStream())
            {
                var editingSession = await EditingSessionFactory.CreateEditingSessionAsync(ms);

                editingSession.AddFilter(SelectedFilter.Creator());
                await editingSession.RenderToWriteableBitmapAsync(PreviewImage);
            }

            // remove unnecessary pixels
            //var removal = ClearTransparent ? Constants.White & 0xFFFFFF : Constants.White;
            // transparent white
            var removal = (0xFF << 24) |
                          (Grayscale << 16) |
                          (Grayscale << 8) |
                          (Grayscale);

            for (var i = 0; i < PreviewImage.Pixels.Length; ++i)
            {
                if (_maskBuffer[i] == 0)
                {
                    PreviewImage.Pixels[i] = removal;
                }

                if (_maskBuffer[i] != 0)
                {
                    MainImage.Pixels[i] = ((Grayscale2 << 16) | (Grayscale2 << 8) | Grayscale2) | ((255 - _maskBuffer[i]) << 24);
                }
                else
                {
                    MainImage.Pixels[i] = _backup.Pixels[i];
                }
            }

#if DEBUG
            try
            {
                using (var fileStream = _isoStore.CreateFile("MainImage.jpg"))
                    MainImage.SaveJpeg(fileStream, ImageWidth, ImageHeight, 0, 100);
                using (var fileStream = _isoStore.CreateFile("PreviewImage.jpg"))
                    PreviewImage.SaveJpeg(fileStream, ImageWidth, ImageHeight, 0, 100);
            }
            catch (Exception e)
            {
                App.LogError(e);
            }
#endif

            using (var ms = MainImage.ToStream())
            {
                Helpers.SafeDispose(ref _editingSession);
                _editingSession = await EditingSessionFactory.CreateEditingSessionAsync(ms);
            }

            using (var ms = PreviewImage.ToStream())
                using (var blendingSession = await EditingSessionFactory.CreateEditingSessionAsync(ms))
                {
                    PreviewImage.Invalidate();

                    _editingSession.AddFilter(FilterFactory.CreateBlendFilter(blendingSession, SelectedBlendFunction));
                    var temp = new WriteableBitmap(MainImage.PixelWidth, MainImage.PixelHeight);
                    await _editingSession.RenderToWriteableBitmapAsync(temp);

                    MainImage = temp;
                    if (SelectedTool != null)
                    {
                        SelectedTool.TargetImage = MainImage;
                    }

                    UndoCommand.RaiseCanExecuteChanged();
                    CanApply = true;
                }

            if (_queued)
            {
                _queued = false;
                ApplyExecute();
            }

            IsWorking = false;
        }
示例#16
0
        private async void ChooseExecute()
        {
            CanChoose = false;
            try
            {
                var chooser = new PhotoChooserTask {
                    ShowCamera = true
                };
                var first = await chooser.ShowAsync();

                if (first.ChosenPhoto == null)
                {
                    var prompt = new ToastPrompt {
                        Message = "Gotta choose something man..."
                    };
                    prompt.Show();
                    return;
                }

                var second = await chooser.ShowAsync();

                if (second.ChosenPhoto == null)
                {
                    var prompt = new ToastPrompt {
                        Message = "Also choose second one..."
                    };
                    prompt.Show();
                    return;
                }

                var bi1 = new BitmapImage();
                bi1.SetSource(first.ChosenPhoto);

                var bi2 = new BitmapImage();
                bi2.SetSource(second.ChosenPhoto);

                WriteableBitmap wb1;
                WriteableBitmap wb2;
                if (bi2.PixelHeight != bi1.PixelHeight || bi2.PixelWidth != bi1.PixelWidth)
                {
                    // sorry for bad croping
                    var toast = new ToastPrompt {
                        Message = "images are not of the same size, lame cropping incoming :/"
                    };
                    toast.Show();

                    EditingSession session1 = null, session2 = null;
                    using (var stream1 = bi1.ToStream())
                        using (var stream2 = bi2.ToStream())
                            try
                            {
                                var task1    = EditingSessionFactory.CreateEditingSessionAsync(stream1);
                                var task2    = EditingSessionFactory.CreateEditingSessionAsync(stream2);
                                var sessions = await Task.WhenAll(task1, task2);

                                session1 = task1.Result;
                                session2 = task2.Result;

                                var cropRect = new Windows.Foundation.Rect(0, 0,
                                                                           Math.Min(bi1.PixelWidth, bi2.PixelWidth),
                                                                           Math.Min(bi1.PixelHeight, bi2.PixelHeight));

                                sessions[0].AddFilter(FilterFactory.CreateCropFilter(cropRect));
                                sessions[1].AddFilter(FilterFactory.CreateCropFilter(cropRect));
                                wb1 = new WriteableBitmap((int)cropRect.Width, (int)cropRect.Height);
                                wb2 = new WriteableBitmap((int)cropRect.Width, (int)cropRect.Height);

                                await Task.WhenAll(
                                    sessions[0].RenderToWriteableBitmapAsync(wb1),
                                    sessions[1].RenderToWriteableBitmapAsync(wb2)
                                    );
                            }
                            finally
                            {
                                Helpers.SafeDispose(ref session1);
                                Helpers.SafeDispose(ref session2);
                            }
                }
                else
                {
                    wb1 = new WriteableBitmap(bi1);
                    wb2 = new WriteableBitmap(bi2);
                }

                // save images
                using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                    using (IsolatedStorageFileStream fileStream1 = isoStore.CreateFile(FirstFileName),
                           fileStream2 = isoStore.CreateFile(SecondFileName))
                    {
                        wb1.SaveJpeg(fileStream1, wb1.PixelWidth, wb1.PixelHeight, 0, 100);
                        wb2.SaveJpeg(fileStream2, wb2.PixelWidth, wb2.PixelHeight, 0, 100);
                    }

                FirstImage  = wb1;
                SecondImage = wb2;

                ApplyExecute();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                CanChoose = true;
            }
        }
        /// <summary>
        /// For the given bitmap renders filtered thumbnails for each filter in given list and populates
        /// the given wrap panel with the them.
        ///
        /// For quick rendering, renders 10 thumbnails synchronously and then releases the calling thread.
        /// </summary>
        /// <param name="bitmap">Source bitmap to be filtered</param>
        /// <param name="side">Side length of square thumbnails to be generated</param>
        /// <param name="list">List of filters to be used, one per each thumbnail to be generated</param>
        /// <param name="panel">Wrap panel to be populated with the generated thumbnails</param>
        private async Task RenderThumbnailsAsync(Bitmap bitmap, int side, List <FilterModel> list, WrapPanel FiltersWrapPanel)
        {
            using (EditingSession session = new EditingSession(bitmap))
            {
                //render filtered photo
                int i = 0;
                foreach (FilterModel filter in list)
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(side, side);

                    //crop the bitmap
                    foreach (IFilter f in filter.Components)
                    {
                        session.AddFilter(f);
                    }

                    Windows.Foundation.IAsyncAction action = session.RenderToBitmapAsync(writeableBitmap.AsBitmap());

                    i++;
                    if (i % 10 == 0)
                    {
                        // async, give control back to UI before proceeding.
                        await action;
                    }
                    else
                    {
                        // synchroneous, we keep the CPU for ourselves.
                        Task task = action.AsTask();
                        task.Wait();
                    }

                    PhotoThumbnail photoThumbnail = new PhotoThumbnail()
                    {
                        Bitmap = writeableBitmap,
                        Text   = filter.Name,
                        Width  = side,
                        Margin = new Thickness(6)
                    };

                    photoThumbnail.Tap += async delegate
                    {
                        ProgressIndicator.IsRunning = true;
                        SetScreenButtonsEnabled(false);

                        App.ThumbnailModel.UndoAllFilters();
                        App.ThumbnailModel.ApplyFilter(filter, _shouldCrop);
                        App.ThumbnailModel.Dirty = true;

                        WriteableBitmap photo = new WriteableBitmap((int)App.ThumbnailModel.Width, (int)App.ThumbnailModel.Height);
                        await App.ThumbnailModel.RenderBitmapAsync(photo);

                        PhotoViewer.Source = photo;

                        SetScreenButtonsEnabled(true);
                        ProgressIndicator.IsRunning = false;
                    };

                    FiltersWrapPanel.Children.Add(photoThumbnail);

                    session.UndoAll();
                }
            }
            ProgressIndicator.IsRunning = false;
        }
        public async Task GetNewFrameAndApplyEffect(IBuffer processedBuffer)
        {
            if (captureDevice == null)
            {
                return;
            }

            captureDevice.GetPreviewBufferArgb(cameraBitmap.Pixels);

            var outputBtm = new Bitmap(
                outputBufferSize,
                ColorMode.Bgra8888,
                (uint)outputBufferSize.Width * 4, // 4 bytes per pixel in BGRA888 mode
                processedBuffer);

            using (var session = new EditingSession(cameraBitmap.AsBitmap()))
            {
                switch (effectIndex)
                {
                    case 0:
                        session.AddFilter(FilterFactory.CreateLomoFilter(0.5, 0.5, LomoVignetting.High, LomoStyle.Yellow));
                        break;
                    case 1:
                        session.AddFilter(FilterFactory.CreateMagicPenFilter());
                        break;
                    case 2:
                        session.AddFilter(FilterFactory.CreateGrayscaleFilter());
                        break;
                    case 3:
                        session.AddFilter(FilterFactory.CreateAntiqueFilter());
                        break;
                    case 4:
                        session.AddFilter(FilterFactory.CreateStampFilter(5, 100));
                        break;
                    case 5:
                        session.AddFilter(FilterFactory.CreateCartoonFilter(false));
                        break;
                }

                await session.RenderToBitmapAsync(outputBtm);
            }
        }
示例#19
0
        private async void SplitImageFromBitmap(WriteableBitmap bmp)
        {
            _session = new EditingSession(bmp.AsBitmap());
            if (playMode == PlayMode.CameraVideo) _session.AddFilter(FilterFactory.CreateStepRotationFilter(Rotation.Rotate90));
            if (playMode == PlayMode.CameraVideo) _session.AddFilter(FilterFactory.CreateCropFilter(new Windows.Foundation.Rect(15, 20, 450, 600)));
            IFilter selectedFilter = GetFilter();
            try
            {
                if (Utils.IsChallengeMode())
                {
                    foreach (Image img in images)
                    {
                        _session.AddFilter(FilterFactory.CreateCropFilter(new Windows.Foundation.Rect(images.IndexOf(img) % 3 * 150, images.IndexOf(img) / 3 * 150, 150, 150)));
                        if (selectedFilter != null ) _session.AddFilter(selectedFilter);
                        await _session.RenderToImageAsync(img, OutputOption.PreserveAspectRatio);
                        if (selectedFilter != null && _session.CanUndo()) _session.Undo();
                        if (_session.CanUndo()) _session.Undo();
                    }
                }
                else
                {
                    foreach (Image img in images)
                    {
                        _session.AddFilter(FilterFactory.CreateCropFilter(new Windows.Foundation.Rect(images.IndexOf(img) % 6 * 75, images.IndexOf(img) / 6 * 75, 75, 75)));
                        if (selectedFilter != null) _session.AddFilter(selectedFilter);
                        await _session.RenderToImageAsync(img, OutputOption.PreserveAspectRatio);
                        if (selectedFilter != null && _session.CanUndo()) _session.Undo();
                        if (_session.CanUndo()) _session.Undo();
                    }
                }

            }
            catch (Exception exception)
            {
                MessageBox.Show("Exception:" + exception.Message);
                return;
            }
            if (playMode == PlayMode.CameraVideo) { processNextFrame(); }

        }
示例#20
0
        private async void SplitImage(Stream stream)
        {
            int dimension;
            _session = await EditingSessionFactory.CreateEditingSessionAsync(stream);
            IFilter selectedFilter = GetFilter();
            if (Utils.IsChallengeMode())
            {
                dimension = 150;
            }
            else
            {
                dimension = 75;
            }
            try
            {
                stream.Position = 0;

                foreach (Image img in images)
                {
                    _session.UndoAll();
                    _session.AddFilter(FilterFactory.CreateCropFilter(new Windows.Foundation.Rect(Canvas.GetLeft(img), Canvas.GetTop(img), dimension, dimension)));
                    if (selectedFilter != null) _session.AddFilter(selectedFilter);                   
                    await _session.RenderToImageAsync(img, OutputOption.PreserveAspectRatio);
                }

                progressbarIndeterminateDownload.Visibility = System.Windows.Visibility.Collapsed;
                progressbarDescription.Visibility = System.Windows.Visibility.Collapsed;
                isLoading = false;
                playButton.Visibility = System.Windows.Visibility.Visible;

            }
            catch (Exception exception)
            {
                MessageBox.Show("Exception:" + exception.Message);
                return;
            }
        }
示例#21
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());
            }
        }
        /// <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;
            }
        }
示例#23
0
        /// <summary>
        /// For the given bitmap renders filtered thumbnails for each filter in given list and populates
        /// the given wrap panel with the them.
        /// 
        /// For quick rendering, renders 10 thumbnails synchronously and then releases the calling thread.
        /// </summary>
        /// <param name="bitmap">Source bitmap to be filtered</param>
        /// <param name="side">Side length of square thumbnails to be generated</param>
        /// <param name="list">List of filters to be used, one per each thumbnail to be generated</param>
        /// <param name="panel">Wrap panel to be populated with the generated thumbnails</param>
        private async Task RenderThumbnailsAsync(Bitmap bitmap, int side, List<FilterModel> list, WrapPanel panel)
        {
            using (EditingSession session = new EditingSession(bitmap))
            {
                int i = 0;

                foreach (FilterModel filter in list)
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(side, side);

                    foreach (IFilter f in filter.Components)
                    {
                        session.AddFilter(f);
                    }

                    Windows.Foundation.IAsyncAction action = session.RenderToBitmapAsync(writeableBitmap.AsBitmap());

                    i++;

                    if (i % 10 == 0)
                    {
                        // async, give control back to UI before proceeding.
                        await action;
                    }
                    else
                    {
                        // synchroneous, we keep the CPU for ourselves.
                        Task task = action.AsTask();
                        task.Wait();
                    }

                    PhotoThumbnail photoThumbnail = new PhotoThumbnail()
                    {
                        Bitmap = writeableBitmap,
                        Text = filter.Name,
                        Width = side,
                        Margin = new Thickness(6)
                    };

                    photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) =>
                    {
                        App.PhotoModel.ApplyFilter(filter);
                        App.PhotoModel.Dirty = true;

                        NavigationService.GoBack();
                    };

                    panel.Children.Add(photoThumbnail);

                    session.UndoAll();
                }
            }
        }